Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the syntax for creating HandleBars helpers server side?

Using Handlebars.Net, I'd like to create a HandlebarsHelper that will replace carriage returns and newlines with <br> tags. It should look something like this:

string pattern = @"/(\r\n|\n|\r)/gm";
string replacement = "<br>";
Regex rgx = new Regex(pattern);

Handlebars.RegisterHelper("link_to", (string text) =>
{
    text = rgx.Replace(text, replacement);
});

The compiler (or resharper) is telling me that it can't tell if I'm trying to use HandlebarsBlockHelper or HandlebarsHelper, and I'm missing arguments in either case.

  1. What's the difference between the two?
  2. I can't seem to find much documentation for any of this. Is there documentation for the above two mentioned objects as well as HelperOptions, and how to use TextWriter, the dymanic context and the argument object list?
like image 305
BobbyA Avatar asked Apr 08 '16 18:04

BobbyA


1 Answers

It ended up looking like this with a little help from the C# Regex class:

var newlineRegx = new Regex("(\\r\\n|\\n|\\r)",RegexOptions.Multiline);

Handlebars.RegisterHelper("handleNewLines", (output, context, arguments) =>
{
    var str = newlineRegx.Replace((string)arguments[0], "<br>");
    output.Write(str);
});

To answer my questions:

  1. HandleBarsBlockHelper provides a mechanism for invoking a helper with a block of the template. Block helpers can then invoke that block zero or more times with any context it chooses. Check out the description for Helpers for more info (at the bottom you'll see a button labeled "Learn More: Block Helpers").

    • TextWriter.Write is how you output your transformed text.
    • context will essentially be the JSON object you passed into the delegate you created with Handlebars.Compile().
    • The argument object lists contains the arguments that appear along side the helper you're defining, which you'll use in your HTML template

To better understand the argument object list, it'll help to see how I used this helper in my HTML template:

<div>
    <p>{{{handleNewLines StringVariable}}}</p>
</div>

Where "StringVariable" is a member of the JSON object I passed into the delegate I created with Handlebars.Compile()

like image 172
BobbyA Avatar answered Oct 23 '22 04:10

BobbyA