HTML - in - JS
The Perfect Site Generator
Programming a simple, static, website is trickier than it looks. The first version is usually quick and easy to write but every subsequent version gets harder and more brittle with each change.
The lessons we have learnt in programming - localise scope, reuse components, calculate values from data - all hit a brick wall when coding a raw websites.
The problem is that HTML/CSS is not a ‘real’ programming language and it is a struggle to get it to behave properly. In response to this problem the programming community quickly moved on from using raw HTML/CSS and created new ways of generating them instead.
We call these ‘templates’ and the way most of them work is to create a new language structure that is some mix of HTML and supporting programming structures - loops, conditionals and so on.
Now these have been excellent solutions and have taken us far yet they all still suffer from two fundamental problems:
- They are not ‘real’ programming languages and hence always lag behind in implementing the full power available to a ‘proper’ language.
- For example, how would you include some package that you found that does really nice Tree-shaking?
- Or embed a new syntax highlighter someone has made?
- Or color the background of a card based on the sentiment of the text in it?
- Developers need to learn this new language and so get the worst of both worlds
- We need to learn a new language and all the little tricks it needs in order to get something non-standard done (hours of googling)
- And what we’ve learned lacks much of the true power of any ‘real’ language like Javascript that we could have leaned instead.
So The Perfect Site Generator would - ideally - require
- No new language or concepts to be learnt
- Allow us to add to HTML/CSS loops, conditionals, functions, scoping - all the good stuff that we’ve discovered we like over these years.
And - with the advent of ES6 - this Magical Perfect Site Generation Option is now a reality!
Just Use Javascript
In ES6 Javascript now provides Template Strings as part of it’s core language. While it is easy to overlook this addition to the language as a “just prettier syntax” Template Strings are pretty powerful things.
What is a template string? Well they are like ‘normal’ javascript strings except that they can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}
). So we can change this string:
'hello there ' + name + '! Great to see you.'
to this
`hello there ${name}! Great to see you.`
The power here comes when we realize that the expression
is fully functional Javascript. That means we can call functions, include packages, do calculations, … - do everything we could do with the full power of Javascript behind us.
The best way to explain it’s power is to provide examples and how-to’s so let’s do that next.
HTML - in - JS for Dummies
(or a quick look at some examples)
1. Use a simple HTML template
let index = `<!doctype html>
<html>
<head>
<title>${title}</title>
</head>
<body>
${content()}
</body>
</html>`
write('index.html', index)
...
let title = 'Welcome to HTML - in - JS'
...
function content() {
return `
<div class=container>
<div class='col col-4'
${sidebar()}
</div>
<div class='col col-8'>
${maincontent()}
</div>
</div>`
}
...
We can see how similar the content above looks like a “template language” but it’s just plain vanilla Javascript.
2. Use Markdown
We all love markdown. It’s a wonderful way of writing text with just enough symbols thrown in to make it pleasing to write and useful to generate.
So how would we use markdown if we wanted in our site? Simple, just write our content in markdown in some file
# First Fig
My candle burns at both ends;
It will not last the night;
But ah, my foes, and oh, my friends --
It gives a lovely light!
*-- Edna St Vincent Millay*
Then use our favorite markdown package to parse it and give us the content we need:
function poem(file) {
return md.render(read(file))
}
3. Loop over table data
This is a classic use case for templates - looping. But now, instead of having to learn a new syntax we use javascript directly.
`<ul>
${data.map(item => `<li>${item}</li>`).join('')}
</ul>`
Helper Functions
When generating HTML-from-JS there are a few operations that are commonly required - reading from disk, saving a file, parsing markdown, using a HTML template, and so on.
Here we have some helper functions that support these common cases which can be used to quickstart your site development (or just as a starting point for anyone who is creating their own).
/* example use */
const helper = require('html-in-js')
function createSite() {
helper.save(helper.md(helper.read('content.md)), 'index.html')
...
}
This is the list of helper functions available:
Function | Description | Notes |
---|---|---|
read | Read data from file | read('content.md') |
lines | Split data into lines | lines(data) Splitting data into lines is useful for processing/filtering and so on |
save | Saves data into file | save(html, path) |
copy | Copies file into deployment | copy(src, dst) |
mkdir | Makes a directory path (recursively) | mkdir(path) |
exec | Executes a command in the default shell (only pass in trusted commands!) | exec(cmd) or exec([cmd,and,args]) : returns (err, {stdout,stderr,exitCode})
Takes an optional options argument that supports all <a href=https://nodejs.org/api/child_process.html#child_processspawnsynccommand-args-options">spawn</a> options. The most useful are { cwd: 'current/working/directory', env: {key:value}, quiet: true } . USE WITH CARE
|
md | Convert markdown into HTML | md('# Hello World!') |
htmlboilerplate | Use HTML 5 Boilerplate | htmlboilerplate() - returns the HTML boilerplate which can then be edited with lines() or edit() htmlboilerplate(location) - saves all required files (jquery, normalize.css,etc) into location (you can update the webmanifest/css/js and save your own favicon and icon.png) |
clean | Cleans/deletes the file/folder passed in | USE WITH CARE |
edit | Can be used to edit a file | edit(line => if(line.match(/sidebar content/)) return sidebar_content()) edit(line => if(line.match/jquery/) return helper.DELETE) |
findAll | Returns all files in a path recursively | findAll('assets','.js') findAll('assets,'js') // Also works findAll('assets') // Don't filter by extension |
Example Site
You can see an example of HTML-in-JS in action here
Your Contribution Welcome
The preceeding examples should have given you a feel for how simple and elegant it is to use HTML-in-JS.
I encourage anyone who believes in html-in-js to contribute more examples and how-to’s to spur ideas and drive html-in-js’s adoption.
Thanks.