Peter Stuifzand

Implicit algorithms in templates

I was thinking about implicit algorithms and implicit datastructures and thought how this applied to templates in web applications. I found that there are a few places where I write the same template code with just a few different pieces.

One of the examples is a piece of code for showing a text field with a few labels around it. This piece of template code is used for almost every field in the product edit (and new) form. This is repeated code, but we should not do this, right?

There are a few parts to one of these pieces of code. It has a textual name, a short description, an input field (which depends on the type of the value) and the actual value in the field.

<p><label for="sku">SKU</label> <span class='description'>Stock keeping unit</span>
<input type="text" id="sku" name="sku" value="[% product.sku %]"></p>

It could look like the above. To get an idea about what an implicit algorithms is, you could say that you’re the computer and the data structure is in your head.

Write 'p' start tag
Write 'label' start tag with 'for' attribute with value 'id of field'
Write name of field
Write 'label' end tag
Write a space
If field has a description
    Write 'span' start tag with 'class' attribute with value 'description'
    Write description of field
    Write 'span' end tag
End
Write 'input' tag with type, id, name and value.
Write 'p' end tag

This piece of pseudocode shows how we run the piece of code in our head. The strange thing is that computers are actually really good at following instructions. A computer could this piece of code better than you could.

This piece of code is implicit in the template. Why didn’t I write it as a piece of code?

There is also an implicit datastructure in there. Maybe something like this:

Field {
    string title
    string name
    string id
    string description
    string type
}

Field { "SKU", "sku", "sku", "Stock keeping unit", "text" }

If I create another line like this field description I can let the computer create a piece of HTML code for me, without thinking about it.

Field { "Name", "name", "name", Name of the product", "text" }

The thing is that by starting to use datastructures and algorithms for this, we can start to write more general functions that can be used for even more parts of your web app. Imagine the possibilities.

© 2023 Peter Stuifzand