<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<div id="content"></div>
<script type='text/template' id='welcome'>
<h1>Welcome, <%= username %></h1>
<p>Today's outlook is <%= outlook %>, with a chance of <%= weather %>. Have a great day!</p>
</script>
JavaScript
// Introduction to Underscore.js -> brings Ruby to JS
var name = "vader",
hobby = "dueling",
food = "anything liquid",
age = 49;
// Step 1: Define a Template (aka a Ruby like view...in JS!)
var story = "<%= name %> enjoys <%= hobby %> while eating <%= food %> and is <%= age %> years old."
// JS object --> Ruby model
var model = {
name: "vader",
hobby: "dueling",
food: "anything liquid",
age: 49
};
// underscore's template method accepts 1 important argument:
// the view - this create a new method
// this new method will now render the view when the model is
// passed in as an argument
// Step 2: Create the Template
var template = _.template(story);
var compiledTemplate = template(model);
// Step 3: render on the page
var content = document.getElementById('content');
content.innerHTML = compiledTemplate;
// Rendering a full template using jQuery
// get the html template from the script/template tag
var newTemplate = $('#welcome').html();
// now we need a model
var newModel = {
username: 'Grand Moff Tarkin',
outlook: 'Grim',
weather: 'the death star blowing up'
};
// Create the Template
var newCompiledTemplate = _.template(newTemplate);
// render on the page
$('#content').append(newCompiledTemplate(newModel));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.