Search code examples
pugtemplate-engine

Example usage of jade runtime.js


I've been looking into using compiled jade templates on the browser. The jade README says:

Through the use of Jade's ./runtime.js you may utilize these pre-compiled templates on the client-side without Jade itself, all you need is the associated utility functions (in runtime.js), which are then available as jade.attrs, jade.escape etc. To enable this you should pass { client: true } to jade.compile() to tell Jade to reference the helper functions via jade.attrs, jade.escape etc.

There are no examples that I could find that use the runtime.js method. I've compiled the templates to individual js files, but how am I supposed to use them? All I have right now is multiple functions called anonymous, and a jade object, which I've no idea how to use.


Solution

  • If you want to use a compiled jade template function on the client side, you must include runtime.js in the page.

    runtime.js provides helper functions which the compiled jade template functions use to render out html. It does this by attaching a variable jade to the window which has several methods which the templates use (e.g, jade.escape).

    For example:

    <script src='runtime.js'> // from jade repository
    <script src='template.js'> // compiled by jade cli
    <script>$('body').append(anonymous({local:'value'))</script> // works!
    

    This will successfully append the rendered html to the body. However...

    <script src='template.js'> // compiled by jade cli
    <script>$('body').append(anonymous({local:'value'))</script> // fails...
    

    This will generally fail with Uncaught ReferenceError: jade is not defined.

    In general, you should probably rename your functions something besides anonymous.