I have some legacy code I'm upgrading Handlebars dotnet on in which we were previously registering a block helper for usage as follows:
{upper}
This will be up-cased
{/upper}
This was being done with the following helper method:
private static void UpperHelper(TextWriter writer, HelperOptions options, dynamic context, params object[] parameters)
{
using (var stringWriter = new StringWriter())
{
options.Template(stringWriter, context);
writer.Write(stringWriter.ToString().ToUpper());
}
}
However, with the new API we no longer can output to a TextWriter:
private static void UpperHelper(EncodedTextWriter output, BlockHelperOptions options, Context context, Arguments arguments)
{
using (var stringWriter = new StringWriter())
{
// error - Cannot convert from StringWriter to EncodedTextWriter
options.Template(stringWriter, context);
output.Write(stringWriter.ToString().ToUpper());
}
}
I've tried everything I can think of to properly create an EncodedTextWriter targetting my stringWriter here, but no go.
I'd appreciate any help in getting this converted over. And while nowadays I wouldn't even register it as a block helper, there's templates in the wild I cannot control so I must keep it as a block helper.
Thanks
Took a bit of digging through the Handlebars.NET source to figure out how to initialize a EncodedTextWriter
, but I managed to get this block helper functionality working.
var handlebarsContext = Handlebars.CreateSharedEnvironment();
handlebarsContext.RegisterHelper("upper", (output, options, context, parameters) =>
{
var formatterProvider = new FormatterProvider(handlebarsContext.Configuration.FormatterProviders);
using var writer = new EncodedTextWriter(
ReusableStringWriter.Get(),
handlebarsContext.Configuration.TextEncoder,
formatterProvider);
options.Template(writer, context);
output.WriteSafeString(writer.ToString().ToUpper());
});
If you're using the global Handlebars context then the first line can be omitted and handlebarsContext
can be replaced with Handlebars
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.