jdiamond / Nustache

Logic-less templates for .NET
MIT License
596 stars 125 forks source link

Nustache - Logic-less templates for .NET

Nustache.Core Nustache.Core

NEW NOTICE - 2015-03-29:

Hello, as you may have noticed this repository has been silent for awhile. I worked on it awhile ago when I had a problem but didn't contribute any more.

I'm planning to commit some time to looking at outstanding pull-requests and issues and try get the project moving again. With that in mind feel free to open issues and contribute pull requests.

NOTICE (JDiamond):

I haven't used Nustache in a while and don't have enough bandwidth to responsibly maintain it. If you depend on Nustache and want committ access, please contact me!

For a list of implementations (other than .NET) and editor plugins, see http://mustache.github.com/.

Installation:

Usage:

For non-MVC projects:

var html = Render.FileToString("foo.template", myData);
var template = new Template();
template.Load(new StringReader(templateText));
var compiled = template.Compile<Foo>(null);

var html = compiled(fooInstance);

For MVC projects:

nustache.exe:

Syntax:

{{<foo}}This is the foo template.{{/foo}}
The above doesn't get rendered until it's included
like this:
{{>foo}}

You can define templates inside sections. They override templates defined in outer sections which override external templates.

Helpers usage:

Helpers may be useful to:

Example: Following line should print time like 13:21:10 instead of default format of DateTime.

{{FormatDateTime FooDateTime format="HH:mm:ss"}}

To get this working use following code before rendering.

Nustache.Core.Helpers.Register("FormatDateTime", FormatDateTime);

And implement the function FormatDateTime, which could look like this:

static void FormatDateTime(RenderContext context, IList<object> arguments, IDictionary<string, object> options, RenderBlock fn, RenderBlock inverse)
{
    if (arguments != null && arguments.Count > 0 && arguments[0] != null && arguments[0] is DateTime)
    {
        DateTime datetime = (DateTime)arguments[0];
        if (options != null && options.ContainsKey("format"))
            context.Write(datetime.ToString(options["format"] as string));
        else
            context.Write(datetime.ToString());
    }
}

Helpers syntax in nustache is HelperName [arguments] [options]. Difference between arguments and options is that the options specifie the tuples key=value while arguments are simple values. If value (from arguments or options) is not closed within double quotes it gets evaluated (e.g. FooDateTime is evaluated to value of the member called FooDateTime, and therefore the argument[0] is of DateTime type. On the other hand the string "HH:mm:ss" is not evaluated.

All arguments and options are separated by spaces and even closed in double-quotes they cannot contain spaces. arguments and options may be mixed (equation sign marks it is option instead of argument).

Development:

git submodule update --init