Debian Codegraph @

examples/client-injection.html

raw
1 <!DOCTYPE html>
2 <!--
3 This example demonstrates how to compile and render EJS templates in the
4 browser. It is usually recommended to always embed a precompiled function
5 in the HTML, rather than compile it on-the-fly, but this demonstrates that
6 it is possible.
7
8 To use this example, first run `jake build` in the EJS root directory to
9 produce the client-side ejs.js and ejs.min.js. Alternatively, you can
10 download the prebuilt client scripts (both minified and not) in GitHub
11 releases.
12 -->
13 <html>
14 <head>
15 <script src="../ejs.js"></script>
16 <!-- `type` can be anything but application/javascript -->
17 <script id="users" type="text/template">
18 <% if (names.length) { %>
19 <ul>
20 <% names.forEach(function(name){ %>
21 <li><%= name %></li>
22 <% }) %>
23 </ul>
24 <% } %>
25 </script>
26 <script>
27 onload = function () {
28 // get the EJS template as a string
29 var templ = document.getElementById('users').innerHTML;
30 console.log('EJS template:');
31 console.log(templ);
32 // data to output to the template function
33 var data = { names: ['loki', 'tobi', 'jane'] };
34 // stores the rendered HTML
35 var html = ejs.compile(templ)(data);
36 console.log('Rendered HTML:');
37 console.log(html);
38 // inject the rendered data to <body>
39 document.body.innerHTML = html;
40 console.log('HTML injected to <body>');
41 }
42 </script>
43 </head>
44 <body>
45 </body>
46 </html>