JSFiddle - React, Tailwind, and code Playground

824 W. Superior St. Unit 510

by Christopher Kim

HTML

<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));