Skip to content

Instantly share code, notes, and snippets.

@nikmartin
Created May 8, 2015 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikmartin/d19c65ae5a07c19bbfef to your computer and use it in GitHub Desktop.
Save nikmartin/d19c65ae5a07c19bbfef to your computer and use it in GitHub Desktop.
Underscore/Lodash template test
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Underscore/lodash template test </title>
<script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<!--whichever one of these is LAST will get assigned to '_'-->
<script data-require="lodash.js@*" data-semver="3.8.0" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>
<script data-require="underscore.js@*" data-semver="1.6.0" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
</head>
<body>
<h1>
Underscore/LoDash Template Test
</h1>
<!-- BEGIN: Underscore Template Definition. -->
<script type="text/template" class="template">
<h3>Library Version (this html should be escaped): <%- '<h1>' + _.VERSION + '</h1>' %></h3>
<h2>
<%- rc.listTitle %>
</h2>
<ul>
<% _.each( rc.listItems, function( listItem ){ %>
<li>
<%- listItem.name %>
<% if ( listItem.hasOlympicGold ){ %>
<em>*</em>
<% } %>
</li>
<% }); %>
</ul>
<% var showFootnote = _.any(
_.pluck( rc.listItems, "hasOlympicGold" )
); %>
<% if ( showFootnote ){ %>
<p style="font-size: 12px ;">
<em>* Olympic gold medalist</em>
</p>
<% } %>
</script>
<!-- END: Underscore Template Definition. -->
<!-- Include and run scripts. -->
<script type="text/javascript">
_.templateSettings.variable = "rc";
// Grab the HTML out of our template tag and pre-compile it.
var template = _.template(
$( "script.template" ).html()
);
// Define our render data (to be put into the "rc" variable).
var templateData = {
listTitle: "Olympic Volleyball Players",
listItems: [
{
name: "Misty May-Treanor",
hasOlympicGold: true
},
{
name: "Kerri Walsh Jennings",
hasOlympicGold: true
},
{
name: "Jennifer Kessy",
hasOlympicGold: false
},
{
name: "April Ross",
hasOlympicGold: false
}
]
};
// Render the underscore template and inject it after the H1
// in our current DOM.
$( "h1" ).after(
template( templateData )
);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment