Search code examples
templatesmustacheractivejs

Ractive / Moustache Template for Head Tag


I have been searching for this all over, but can not find an answer or example.

Can a Ractive template be used to construct head elements that are consistant across pages, and can that be loaded from a separate file?

For example: all html, head, and title tag info is loaded via a referencable template from an external file into an index page. +html+ +head+ +title+ +/title+ +/head+

And if so, how do you do it? As I try to wrap my head around it, jquery and ractive.js would need to load. Is there a different/better solution?


Solution

  • It is possible. But it's not practical and it raises other issues.

    Here's a basic implementation that shows how <head> can be templated but without concentrating on putting the template in an external file. This works for me in Chrome and IE.

    <html>
    
    <head id="output"></head>
    <script id="template" type="text/html">
        <title>{{ title }}</title>
    </script>
    
    <script type="text/javascript" src="ractive.min.js"></script>
    <script type="text/javascript">
        var ractive = new Ractive({
            template: "#template",
            el: "#output",
            data: {
                title: "This is the title"
            }
        });
    </script>
    
    <body>
        ...
    </body>
    </html>
    

    You'll run into problems with this approach because the head elements won't be loaded until after the page has loaded and Ractive kicks in. This may cause the following problems:

    • Search engines might not be able to read the page title and meta tags
    • Any javascript you need to load into <head> may not work (I tried some simple examples and was able to get the javascript to run but it failed to reference any elements in the body. Maybe it's a context issue and maybe Ractive has support to overcome this but this is an area I'm unfamiliar with.)
    • If you require valid HTML, this probably won't work for you because script tags can't be direct children of <html>, and <head> is supposed to have <title> as a direct child.

    You're better off using a server-side solution to template <head>.