Templates are useful for providing text content with some dynamic elements. They are primarily used in conjunction with HTML Template Plugins to provide HTML content, but can be used for any type of content which is served by a plugin. HTML template plugin content is automatically run through the template processor. To use templating with any other type of plugin, you must call the processor manually.

A template may contain expressions and tags. Expressions get evaluated and replaced with values when the template is processed, while tags control the logic of the template.

Below is an example of a simple template:

<html>

  <head>
    <title>{%= Title %}</title>
    {%= Header %}
  </head>

  <body>

    {% if IsAuthenticated %}
      <h1>Hello {%= UserName %}!</h1>
    {% endif %}

    {%= Body %}

  </body>

</html>

Expressions

Expressions are simply ClassAd expressions which take one of the following two forms: {%= MyExpression %} or {%% MyExpression %}. Both will evaluate the expression ‘MyExpression’ in a context provided by the plugin which is calling the template processor. The only difference between the two is that {%= MyExpression %} may be escaped (the method of escaping can be set based on the context), while {%% MyExpression %} is always interpreted as straight text.

If you are not sure about which to use, use {%= MyExpression %}. This is the safest in general. For instance, if you are generating HTML, characters like &lt; or &gt; will be escaped so they show up properly. If you use {%% MyExpression %} when you mean {%= MyExpression %}, the problem will not be evident unless you happen to output a character that should be escaped. On the other hand, if you use {%= MyExpression %} when you mean {%% MyExpression %} it will be clear because you will see the HTML displayed instead of interpreted.

Tags

Tags provide the ability to add simple logic to a template, and look like this: {% tag %}. Types of tags include conditionals, loops and comments.

Conditionals

Conditional tags take the following form:

{% if Expression %}
  Do something
{% elif Expression2 %}
  Do another thing
{% else %}
  Do something else
{% endif %}

Comments

Comments must be a single line and look like this:

{%# This is a comment! %}

Loops

Loops may be used to iterate over lists or records (ads) in the following ways:

Looping through a list:

Printing the model of each car…

{% for car in cars %}
  {%=car.model%}
{% endfor %}

Looping through a record is very similar to looping through a list. The difference is that the object each iteration produces is a special object with two attributes: name and value.

Printing all attributes of each car…

{% for car in cars %}
  {% for item in car %}
    Name: {%=item.name%} | Value: {%=item.value%}
  {% endfor %}
{% endfor %}