Wanted: better templating language

Posted in Technicalon Feb 25, 2008

I need a better templating language, one where an included (called) template can change its containing (caller) template. For example, consider this container template:

<html>
<head>
<title>{define-spot name="title"}</title>
<script language="Javascript">
{define-spot name="js"}
</script>
</head>
<body>
{include file="inside.tpl"}
</body>
</html>

This container creates a spot where a title can be placed and where some javascript can be placed. It then includes another template file which will put content in those spots. This included template, inside.tpl, would look like the following:


{fill-spot id="title"}Jacob's Super Page{/fill-spot}
{fill-spot id="js"}alert('hello'};{/fill-spot}
<h1>Hello</h1>
<p>This is a sample template file</p>

The template language would also need to be flexible enough such that if the included template didn’t fill the spots, then things continue to work without without crashing, as if the spots had been filled with nothing.

The problem is that many template language translate their template into some sort of source code, and usually that source code turns out to be in a procedual language. This means that templates are parsed from top to bottom, so by the time the inside template is included, the template parser has already parsed the spots above it, and can’t go back and fill those spots (because that would require parsing the container template twice).

A posible solution may be available in some template language which would allow you to parse the inner template first by placing it at the top of the container template, capturing its output, and displaying it later. This would result in a less-elegant container template that might look like the following:


{capture to="inside-contents"}
{include file="inside.tpl"}
{/capture}
<html>
<head>
<title>{define-spot name="title"}</title>
<script language="Javascript">
{define-spot name="js"}
</script>
</head>
<body>
{show id="inside-contents}
</body>
</html>

Comment Form

Categories