Skip to content

Instantly share code, notes, and snippets.

@mattborn
Created April 20, 2017 04:46
Show Gist options
  • Save mattborn/a279d23b229858594cfe4a9cf8013324 to your computer and use it in GitHub Desktop.
Save mattborn/a279d23b229858594cfe4a9cf8013324 to your computer and use it in GitHub Desktop.
Inline templates
<!doctype html>
<html>
<head>
<title>Inline templates</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<style>
body {
font-size: 200%;
margin: 10%;
}
code { background: #eee; }
</style>
</head>
<body>
<div id="render"></div>
<p>This gist shows how to use an inline HTML <code>&lt;template&gt;</code> with <a href="https://lodash.com/docs/4.17.4#template">lodash</a> <code>_.template</code>.</p>
<template id="template">
<h1>Hello {{ what }}!</h1>
</template>
<script src="scripts.js"></script>
</body>
</html>
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
const x = document.createElement('div');
x.append(document.getElementById('template').content);
const template = _.template(x.innerHTML.trim());
document.getElementById('render').innerHTML = template({what: 'World'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment