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

Reply via email to