URL Templating

URL Templating enables you to dynamically rewrite URLs in your HTML content, using an easy-to-understand templating langauge.

This allows you to have a static (i.e., cacheable) Web page that has dynamic context- and user-sensitive URLs in it.

The Basics

To start using URL Templating, first download a copy of the library and mkae it available on your site;

Download: url_template.js (version 0.6)

Now, in each page where you want to use it, add a script tag to the top (changing it to point to your copy):

  <script type="text/javascript" src="url_template.js"></script>

An URL template can appear on almost any HTML element that has an URL for an attribute value. The template itself is located in an attribute of the same name, with _template appended.

For example, the a element has an URL in its href attribute. A templated version of an a element might look like

  <a href="default.html" 
   href_template="/users/{cookie:username}.html">
    your page
  </a>

Here, the a element's href attribute will be dynamically replaced, as the page is loaded, with a URL that has the value of the cookie:username variable interpolated.

Variable Interpolation

Template variables are enclosed by {braces}, and are classified by the portion of the name before the first period. The current variable types are:

cookies
Cookies from the browser's current context; e.g., {cookie:userid}.
JSON
Values loaded from a JSON file on the same site; e.g., {json:prefs.userid}.

JSON files are loaded in the document's head section with a link tag;

  <link rel="template_store" type="application/json"
   href="user_pref.json" title="prefs" />

the title attribute controls the namespace that the JSON is loaded into; in this case, it will be available as json.prefs.

template_store link tags may contain templates themselves.

Fallback

By default, if there is a problem dereferencing a variable in a template, the element's normal, untemplated value will be used; for example, in this case:

  <a href="/default.html" href_template="/users/{cookie:userid}">home</a>

if the cookie:userid variable cannot be found, "/default.html" will be used for the src attribute.

However, url_template allows you to customise this behaviour.

If a link tag with a template_redirect relation is found in the document's head section, the browser will be sent to that URI in the case of variable interpolation problems. For example,

  <link rel="template_redirect" href="/login.html" />

Otherwise, if a meta element with a name of template_default is found, the content will be used in the place of missing variables. For example,

  <meta name="template_default" content="new" />
  ...
  <a href="/default.html" href_template="/users/{cookie:userid}">home</a>

In this case, if cookie:userid is not found, the href will be "/users/new".

In all cases, if the browser does not have JavaScript enabled, the untemplated URI will be used.

Plans for the Future

In no particular order: