A note about client-side-only JavaScript in Set templates


Set is a free and open source unobtrusive DOM-based JavaScript template engine based on Distal/Zope. On the server, it uses JSDOM on Node.js to render templates.

The advantages of this approach include:

  • Working with fully-formed, valid HTML5 templates.
  • Using the same template on the server and on the client.

Due to the second feature, it means that if you have inline JavaScript that you want to run only on the client-side (e.g., JavaScript that manipulates the DOM to provide some progressively enhanced functionality like truncating articles with a More… link), you must specifically make sure that it doesn’t run on the server during template substitution.

To do this, check that the script that you only want to run on the client is not running under Node of JSDOM with a line similar to:

if (!navigator.userAgent.includes("Node.js") && !navigator.userAgent.includes("jsdom")) {
  // Client-side-only logic goes here.

If you haven’t given Set a shot, please do. Unlike other DOM-based JS template systems, Set is:

  • DRY: You do not have to write mapping code
  • Actively developed
  • Actively deployed in Better (to render the content for the site and for the app)

Additionally, while Set doesn’t have built-in support for partials, it can support it. Here’s a snippet from Better Builder:

partial: (fullHTML) -> (fullHTML.replace '<html><head></head><body>', '').replace('</body></html>', '')

# …

# Render the page.
headerPartialHTML = @partial(set.render(@theme.header, {navigationList: @navigationList selectedItem}))
pageHTML = set.render(@theme.page, {title: titleOfPage, header: headerPartialHTML, content: content, category: category})

Play with the examples online and learn more about Set on Ind.ie Labs.

Thoughts, suggestions, and pull requests welcome.