jehugaleahsa / mustache-sharp

An extension of the mustache text template engine for .NET.
The Unlicense
306 stars 78 forks source link

Added the ability to register a helper like in Handlebars, e.g. {{myHelper someField}} #43

Closed nickytonline closed 9 years ago

nickytonline commented 9 years ago

Currently in mustache# you can create custom tags, the equivalent of helpers in Handlebars. However the syntax is not the same in some cases. For example in Handlebars if I want to create a custom expression helper to format a phone, I would register it like this

modifyHandlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
    phoneNumber = phoneNumber.toString();

    return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
});

and in my code, I would use it like so.

<div>Phone: {{formatPhoneNumber phoneNumber}}</div>

In mustache#, the formatPhoneNumber tag needs to be prefixed with # for it to work, e.g.

<div>Phone: {{#formatPhoneNumber phoneNumber}}</div>

which is fine if you are only rendering this template on the server. However, the project I'm on is rendering the template on the server and the client. If you keep with the format

<div>Phone: {{#formatPhoneNumber phoneNumber}}</div>

on the client-side, Handlebars will throw an error, i.e.

var verifyMatch = function(open, close) {
    if(open.original !== close.original) {
        throw new Handlebars.Exception(open.original + " doesn't match " + close.original);
    }
};

I created a separate regex for this so as to not interfere with existing functionality in mustache#. To keep things uniform on the server-side and client-side, I propose to allow the expression helper syntax on the server-side as well.

jehugaleahsa commented 9 years ago

I'm not trying to create a server side-compatible version of handlebars. I can understand why you'd not want to have two different templates. If you're shooting for absolute identical functionality, you might consider using node.js.

nickytonline commented 9 years ago

@jehugaleahsa , thanks for your feedback. I use node in another project, but this project is on the .NET stack. I will continue with my fork making any other changes required to maintain isomorphic templating.

Regards, Nick

jehugaleahsa commented 9 years ago

Calling into Node.js using .NET is awkward, I agree. My biggest concern is backward compatibility. Without the #, my code wouldn't know if the name was referring to a key or a tag name. I wouldn't want to break someone else's code if they happened to have a key with the same name as one of their tags.