DamianEdwards / RazorSlices

Lightweight Razor-based templates for ASP.NET Core without MVC, Razor Pages, or Blazor.
MIT License
297 stars 12 forks source link

Support rendering slices to a StringBuilder #12

Closed DamianEdwards closed 1 year ago

DamianEdwards commented 1 year ago

E.g.

public static ValueTask RenderAsync(this RazorSlice slice, StringBuilder stringBuilder, HtmlEncoder? htmlEncoder = null);
madeyoga commented 1 year ago

Hi Damian! I had a quick question about the best way to implement this.

My initial idea was to use StringWriter like the following:

public static ValueTask RenderAsync(this RazorSlice slice, StringBuilder stringBuilder, HtmlEncoder? htmlEncoder = null)
{
  using var sw = new StringWriter(stringBuilder);
  var task = slice.RenderAsync(sw, htmlEncoder);
  if (task.IsCompletedSuccessfully)
  {
    return ValueTask.CompletedTask;
  }
  return task;
}

However, I'm not entirely sure if this is the most efficient approach. Do you have any recommendations?

DamianEdwards commented 1 year ago

I think that's a fine approach. While it's going through a few layers (IBufferWriter<byte> -> TextWriter -> StringWriter -> StringBuilder) they should all be simply passing along to the next layer as much as possible.

You should be able to just return the task result of calling RenderAsync directly though, no need for the IsCompletedSuccessfully check as you don't need to go async.

madeyoga commented 1 year ago

Thank you for your response! I will proceed with the StringWriter approach. May I submit a pull request for this feature? Please let me know if you have any further suggestions or requirements for the implementation.

DamianEdwards commented 1 year ago

Please go ahead!

DamianEdwards commented 1 year ago

This was done and shipped in v0.6.0