Temple: Compile time, embedded D templates
yazd
yazan.dabain at gmail.com
Wed Jan 1 22:58:59 PST 2014
On Thursday, 2 January 2014 at 01:12:24 UTC, Dylan Knutson wrote:
> On Wednesday, 1 January 2014 at 13:04:27 UTC, Jacob Carlborg
> wrote:
>> On 2013-12-31 07:05, Dylan Knutson wrote:
>>> Hello,
>>>
>>> A few months ago I had posted a project of mine, templ-d. It
>>> was an
>>> experiment in writing a template engine for embedding D code
>>> in
>>> arbitrary text files, a-la Vibe.d's Diet templates, but
>>> without the
>>> requirement of generating HTML.
>>>
>>> So, I've revamped templ-d, and written Temple in its place.
>>> It supports
>>> all the neat stuff that a template engine should, including
>>> (but not
>>> limited to!)
>>
>> Does it support any kind of helpers, like Rails do?
>
> It didn't before, because of how the semantics of eRuby syntax
> works, but now it does! It seemed like an important thing to
> support...
>
> Here's an example mimicking a subset of Rails' `form_for`
> helper:
>
> ```d
> <%
> import std.string;
> struct FormHelper
> {
> string model_name;
>
> auto field_for(string field_name, string type="text")
> {
> if(model_name != "")
> {
> field_name = "%s[%s]".format(model_name, field_name);
> }
>
> return `<input type="%s" name="%s" />`.format(type,
> field_name);
> }
>
> auto submit(string value = "Submit")
> {
> return `<input type="button" value="%s" />`.format(value);
> }
> }
>
> auto form_for(
> string action,
> string name,
> void delegate(FormHelper) block)
> {
> auto form_body = capture(block, FormHelper(name));
> return `
> <form action="%s" method="POST">
> %s
> </form>`.format(action, form_body);
> }
> %>
>
> <%= form_for("/shorten", "", (f) { %>
> Shorten a URL:
> <%= f.field_for("url") %>
> <%= f.submit("Shorten URL") %>
> <% }); %>
>
> <%= form_for("/person", "person", (f) { %>
> Name: <%= f.field_for("name") %>
> Age: <%= f.field_for("age") %>
> DOB: <%= f.field_for("date_of_birth", "date") %>
> <%= f.submit %>
> <% }); %>
> ```
>
> Renders:
> ```
> <form action="/shorten" method="POST">
> Shorten a URL:
> <input type="text" name="url" />
> <input type="button" value="Shorten URL" />
> </form>
>
> <form action="/person" method="POST">
> Name: <input type="text" name="person[name]" />
> Age: <input type="text" name="person[age]" />
> DOB: <input type="date" name="person[date_of_birth]" />
> <input type="button" value="Submit" />
> </form>
> ```
>
> This change is present in the latest release of Temple
How much of this is done at compile-time? I would guess that the
code is compiled but it is evaluated on each render. Is that
correct? Is there a way to force compile-time evaluation of at
least part of the template which does not depend on a runtime
value? Or is it completely dependant on an optimizing compiler to
do this work?
More information about the Digitalmars-d-announce
mailing list