Class | Mustache::Generator |
In: |
lib/mustache/generator.rb
|
Parent: | Object |
The Generator is in charge of taking an array of Mustache tokens, usually assembled by the Parser, and generating an interpolatable Ruby string. This string is considered the "compiled" template because at that point we‘re relying on Ruby to do the parsing and run our code.
For example, let‘s take this template:
Hi {{thing}}!
If we run this through the Parser we‘ll get these tokens:
[:multi, [:static, "Hi "], [:mustache, :etag, "thing"], [:static, "!\n"]]
Now let‘s hand that to the Generator:
>> puts Mustache::Generator.new.compile(tokens) "Hi #{CGI.escapeHTML(ctx[:thing].to_s)}!\n"
You can see the generated Ruby string for any template with the mustache(1) command line tool:
$ mustache --compile test.mustache "Hi #{CGI.escapeHTML(ctx[:thing].to_s)}!\n"
Given an array of tokens, converts them into Ruby code. In particular there are three types of expressions we are concerned with:
:multi Mixed bag of :static, :mustache, and whatever. :static Normal HTML, the stuff outside of {{mustaches}}. :mustache Any Mustache tag, from sections to partials.
To give you an idea of what you‘ll be dealing with take this template:
Hello {{name}} You have just won ${{value}}! {{#in_ca}} Well, ${{taxed_value}}, after taxes. {{/in_ca}}
If we run this through the Parser, we‘ll get back this array of tokens:
[:multi, [:static, "Hello "], [:mustache, :etag, "name"], [:static, "\nYou have just won $"], [:mustache, :etag, "value"], [:static, "!\n"], [:mustache, :section, "in_ca", [:multi, [:static, "Well, $"], [:mustache, :etag, "taxed_value"], [:static, ", after taxes.\n"]]]]
Fired when we find an inverted section. Just like `on_section`, we‘re passed the inverted section name and the array of tokens.
Fired when the compiler finds a partial. We want to return code which calls a partial at runtime instead of expanding and including the partial‘s body to allow for recursive partials.