WordBash

The WordPress clone written in GNU Bash

header image
Posted on Jan 6, 2014 11:12AM

Web Templates

A Web Template Non-Engine

I have seen it written that templates cannot be implemented in Bash. Well, "The impossible takes a little longer," someone once said. But it actually did not take me all that long to create a true web template API of about 100 lines.

First, there exists global site data such as this:

bash code

sitebase=${SCRIPT_NAME%/*}

sitehost="http://$HTTP_HOST$REQUEST_URI"

sitedesc="Syntagmatic Personal Publishing Platform"

sitename="WordBash"

sitetitle="The first WordBash site"

A basic template, which comes from a file, is like this:

text='<!DOCTYPE html>
<title>$sitetitle</title>
<link rel="stylesheet" type="text/css" href="$sitebase/style.css">
<header>
<h1><a href="$sitehost" title="$sitetitle">$sitename</a></h1>
<h2>$sitetitle</h2>
</header>'

Just what is a this for anyway?

It is to display the HTML with the variable references replaced by the actual data during run-time. Doing so takes what is known as an "engine". Why? It generally takes a lot of code to do it. A lot of code.

It can be done in Bash like this:

bash code

text=${text//\"/\\\"}

eval "text=\"$text\""

echo "$text"

Of course, the full WordBash "engine" is implemented as a library, Object Oriented and with a rich API. Not only does it support (true) HTML templates, it has caching, display and substitution by arguments and macro-like capabilities while being easy to understand and to maintain.

What is does not have are code-like constructs or special "loop" codes. But that is because it does not have to. A WordBash theme is not implemented like a WordPress theme, only the result is the same.

Some of the code though does have in-line string literals throughout. Such strings should be placed into a template (or a language file). WordBash Demo is a very minimal version.

You may be thinking that eval is dangerous. The code performs an assignment of data only. (Trying to put all manner of code and/or data in a comment or post would be an appropriate test.)

Update: July 2023

One should never "fear" a programming construct. Sure one needs to be careful with parsing externally provided data. But that is 100% different from parsing your own data, read locally from your own file system, written by your own people.

Of course though, one can also simply extract $words from data and then replace them with namerefs or from an associative array. Using eval is actually because I am lazy. But in this context it's fine.

0 Comments
Leave a Reply

Comment length is limited, all HTML will be stripped and do not submit links.

0m0.022s 0m0.030s 0m0.004s 0m0.005s