Code Monkey home page Code Monkey logo

mustachio's Introduction

Mustachio Logo

Mustachio

Nuget

A lightweight, powerful, templating engine for C# and other .net-based languages.

What's this for?

Mustachio allows you to create simple text-based templates that are fast and safe to render. It's the heart of Postmark Templates, and we're ecstatic to provide it as Open Source to the .net community.

How to use Mustachio:

// Parse the template:
var sourceTemplate = "Dear {{name}}, this is definitely a personalized note to you. Very truly yours, {{sender}}"
var template = Mustachio.Parser.Parse(sourceTemplate);

// Create the values for the template model:
dynamic model = new ExpandoObject();
model.name = "John";
model.sender = "Sally";

// Combine the model with the template to get content:
var content = template(model);

Extending Mustachio with Token Expanders:

// You can add support for Partials via Token Expanders.
// Token Expanders can be used to extend Mustachio for many other use cases, such as: Date/Time formatters, Localization, etc., allowing also custom Token Render functions.

var sourceTemplate = "Welcome to our website! {{{ @content }}} Yours Truly, John Smith.";
var stringData = "This is a partial. You can also add variables here {{ testVar }} or use other expanders. Watch out for infinite loops!";
var tokenExpander = new TokenExpander
    {
        RegEx = new Regex("{{{ @content }}}"), // you can also use Mustache syntax: {{> content }}
        ExpandTokens = (s, baseOptions) => Tokenizer.Tokenize(stringData, baseOptions) // Instead of baseOptions, you can pass a new ParsingOptions object, which has no TokenExpanders to avoid infinite loops.
    };
var parsingOptions = new ParsingOptions { TokenExpanders = new[] { tokenExpander } };
var template = Mustachio.Parser.Parse(sourceTemplate, parsingOptions);

// Create the values for the template model:
dynamic model = new ExpandoObject();
model.testVar = "Test";

// Combine the model with the template to get content:
var content = template(model);

Installing Mustachio:

Mustachio can be installed via NuGet:

Install-Package Mustachio
Key differences between Mustachio and Mustache

Mustachio contains a few modifications to the core Mustache language that are important.

  1. each blocks are recommended for handling arrays of values. (We have a good reason!)
  2. Complex paths are supported, for example {{ this.is.a.valid.path }} and {{ ../this.goes.up.one.level }}
  3. Template partials are supported via Token Expanders.
A little more about the differences:

One awesome feature of Mustachio is that with a minor alteration in the mustache syntax, we can infer what model will be required to completely fill out a template. By using the each keyword when interating over an array, our parser can infer whether an array or object (or scalar) should be expected when the template is used. Normal mustache syntax would prevent us from determining this.

We think the model inference feature is compelling, because it allows for error detection, and faster debugging iterations when developing templates, which justifies this minor change to 'vanilla' mustache syntax.

mustachio's People

Contributors

304notmodified avatar atheken avatar derekrushforth avatar infotexture avatar jchoca avatar nickcanz avatar vladsandu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mustachio's Issues

How to check for unsatisfied tokens

I need to check if a template might have tokens that are not provided with the value object.

Based on the example from the readme I tried to capture the missing tokens with a token expander but I wasn't able to find a solution...

// You can add support for Partials via Token Expanders.
// Token Expanders can be used to extend Mustachio for many other use cases, such as: Date/Time formatters, Localization, etc., allowing also custom Token Render functions.

var sourceTemplate = "known = {{known}}, nested known = {{whatever.a}}, unknown = {{nothing}}";
var tokenExpander = new TokenExpander
{
	RegEx = new Regex("{{.*}}"), // you can also use Mustache syntax: {{> content }}
	Renderer = (string s, Queue<TokenTuple> q, ParsingOptions po, InferredTemplateModel itm) =>
		(sb, co) => {
			var ss = s;
			var qq = q;
			var poo = po;
			var itmm = itm;
			
			// somewhere here
		},
	Precedence = Precedence.Low
};
var parsingOptions = new ParsingOptions { TokenExpanders = new[] { tokenExpander } };
var template = Mustachio.Parser.Parse(sourceTemplate, parsingOptions);

// Create the values for the template model:
dynamic model = new ExpandoObject();
model.known = "Test";
model.whatever = new ExpandoObject();
model.whatever.a = "aa";

// Combine the model with the template to get content:
string content = template(model);

Console.WriteLine(content);

Could you guide me please?

Show/display paragraph

Hi guys,

I cant find a way to show/hide a paragraph base if a node exist or not.

My json is

{
  "organization": {
    "name": "name_Value",
    "id": "id_Value"
  },
  "credit": {
      "reason": "Promo code",
      "amount": "333"
  }
}

And part of the template

 <p>You have been invited to {{organization.name}}!  Click here to activate your account and to create your first project. {{#credit}}{{credit.reason}} credit of ${{credit.amount}} has been applied. {{/credit}} </p> 

What Im doing wrong?

Nesting help

I have a template like so:

<table border="1" class="alternate">
    <thead style="background-color: #aaa8f0">
        <th>Station Name</th>
        {{#each abbrevs}}
        <th>{{name}}</th>
        {{/each}}
    </thead>
    <tbody>
        {{#each orders}}
        <tr>
           <td>{{station}}</td>
        </tr>
        {{/each}}
    </tbody>
</table>

And then my data model has something like this:

{
  "abbrevs" : [
     { "name" : "ud" },
    { "name" : "dp" }
  ],
  "orders: [
     {
        "station" : "...",
       "ud" : 1,
       "dp" 2
    },
    {
      ...
    }
  ]
}

So in the headers I'm adding a column for each of the abbrevs names. Now, when I'm looping through my orders, I'm not sure how to put the proper value in the proper column for the order.

#each property value is not shown

Hey,

I tried to use the each argument by using:

{{#each LoggerExceptions}} <div class="row"> Message: {{Message}} </div> {{/each}}

but it does not seem to emit the values of each item in the collection. the each itself does work and is omitting multibel div's but non is filled with values

Add support for uint, ushort, and ulong

I am enjoying mustachio a lot! I am hoping that support for ushort, uint, and ulong could be added in the near future. Currently, those datatypes are not considered valid values. Could it have something to do with the _printableTypes in ContextObject.cs?

Referring to individual array element

I have given model

{
   "array": [ "foo", "bar", "fizz", "buzz"]
}

in mustache.js you can access individual array elements with this syntax: {{array.2}} which should return "fizz". I tried it with Mustachio and unfortunately it doesn't work. It just interpolates to nothing, no exceptions thrown.
Is there a working way of doing this in Mustachio? If not is there an argument against it?

JavaScript port

It would be nice to render Mustachio templates on the front-end. Mustache.js already exists -- I wonder if it's possible to modify it to make Mustachio.js? Has someone already done this?

{{.}} not working

Seems pretty obvious but it's not working:

{{#each choices}} <li class="item-choice">{{#price}}+{{.}}{{/price}}</li> {{/each}}

price exists, I see the character "+" being rendered but nothing after that

{{.}} not working for lists, take 2

I know that the author of #5 says it’s working when you send an actual email, but I have been unable to get it to work, either in the preview renderer or in a delivered email.

I’m using the template

{{#list}}
  {{.}}
{{/list}}

and the JSON

{
  "list": [
    "xxx",
    "yyy",
    "zzz"
  ]
}

I’m just getting an empty body, in the preview and the delivered email. What gives, am I doing something wrong? This works out on the mustache demo page: https://mustache.github.io/#demo.

Framework

Hi,
is the last package 2.1.0 releated to net framework 2 only? the nuGet Package limit its installation

Github topics

This library looks great!

I would recommend to add some topics on Github, so it's easier to find :)

image

How do you render when the variable could be an single object or an array of objects?

Hi,

Here is the issue i am having. Lets say we have an API return a data object which could be either
this

{
    to : {  name : 'John'  }
}

or this

{
    to : [ 
             {  name : 'John'  },
             {  name : 'Jenny'  },
             {  name : 'Markl'  }
          ]
}

How do i render this on a template? If i use something like this.

To:  {{#each to}} {{name}} , {{/each}}

I get the error,

'to' is used like an array by the template, but is a scalar value or object in your model.

What am i missing? Couldn't really find this in the documentation

Conditional if inside another if

Please tell me how can I achieve something like this:

if true
  if true
    // do smth
  end
end

{{#var1}}
  {{#var2}}
    Tadaam: I am here
  {{/var2}}
{{/var1}}

Cannot use Inverted Group inside Inverted Group.

I'm trying to render some default text in case neither of two variables exists.
I expected this to work, but it doesn't. Am I missing something or is this not supported?

{{^foo}}
  {{^bar}}  foo and bar are both missing {{/bar}}
{{/foo}}

Templating fails if there is a not clause

If my template is :

    Hi, your name is {{name}}
    {{^name}} hidden from everyone{{/name}}

It works when the object passed in is {{ "name": null }} (as in, it renders 'Hi, your name is hidden from everyone')

But if I pass in {{ "name": "bob" }} it renders nothing

I get similar results with

Hi, your name is
{{#name}} {{.}} {{/name}}
{{^name}} hidden from everyone{{/name}}

There's no published spec for mustachio

Hi,

I'm working on a tool that can be used to parse postmark server email templates and generate typedefs for the template model that can help guide devs in their code editor on what variables to not miss and what the structure of their template model should be like (array, objects, string, etc) when sending email with a specific template.

This requires me to write a minimalistic parser that parse the template tags, etc, but there's no published spec provided for mustachio. I've learned mustachio extends the popular ruby mustache specs, but where are these extensions defined?

I'd really appreciate your help.

PS: I think it will be a great tooling to know what the template model should look like right in the code editor and I won't mind any collaborations. I already have a working prototype.

Error occurs while parsing tag names containing hyphen-minus characters ("-", unicode number: U+002D)

Wanted to use GUIDs as tag names, but have a trouble with parsing them - the following exception occurs: Mustachio.IndexedParseException: The path '110E6231-BA3E-40DD-AF62-9802DCC02B61' is not valid. Please see documentation for examples of valid paths.
However when I remove all dashes from the tag name all works successfully. Is that an intentional feature or rather a bug?

Code example:

var guidTemplate1Txt = "There was GUID with dashes: {{110E6231-BA3E-40DD-AF62-9802DCC02B61}}";
var guidTemplate2Txt = "There was GUID w/o dashes: {{110E6231BA3E40DDAF629802DCC02B61}}";

var template1 = Mustachio.Parser.Parse(guidTemplate1Txt);
var template2 = Mustachio.Parser.Parse(guidTemplate2Txt);

var model1 = new Dictionary<string, obj>() { { "110E6231-BA3E-40DD-AF62-9802DCC02B61", "content" } };

var model2 = new Dictionary<string, obj>() { { "110E6231BA3E40DDAF629802DCC02B61", "content" } };

var content1 = template1(model1); // Mustachio.IndexedParseException is thrown there
var content2 = template2(model2); // Works successfully

Grunt task to render Mustachio templates

My team uses MailMason and Postmark, to manage all our transactional email templates.

Request:

I would like to have a grunt task that takes my generated .html Mustachio templates, and renders them with a variables file, e.g. variables.json.

This functionality exists for both Handlebars (grunt-compile-handlebars) and Mustache (grunt-mustache-render). But I can't seem to find a prebuilt way to do this for Mustachio.

My use case:

  • I start with .hbs files, then automatically generate the .html/.txt templates, then test them manually in the Postmark console with predefined variables, then upload them from the command line.
  • Instead of the manual step, I would like to automatically send myself the generated emails, with all the sample variable values filled in.

I would suspect other Postmark customers have this same use case. Can you please let me know if a solution already exists for this? Sorry if a Github Issue was not the right way to handle this request. Thanks! 🙌

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.