Search code examples
javascriptbackbone.jshandlebars.jshandlebarshelper

Executing javascript loaded in <script> tag directly in source page


I have to dynamically fetch javascript file which only contains handlebars helper functions. This will be fetched in an html file which will includes the template.

Dynamic file (handlebar_helper_load.js):

import handlebars from 'handlebars';

handlebars.registerHelper('**fullName**', function(person) {
            return person.firstName + " " + person.lastName;
})

Backbone view file :

import handlebars from 'handlebars';

export default View.extend({
    template: template,

    onRender() {
        var imported = document.createElement('script');

        // This will load the above file in script tag on this page 
        imported.src = '**handlebar_helper_load.js**';
        document.head.appendChild(imported);

        // This is the handlebars template
        var source   = '<div class="post">\n' +
                        '  <h1>By {{fullName author}}</h1>\n' +
                        '  <div class="body">{{body}}</div>\n' +
                        '\n' +
                        '  <h1>Comments</h1>\n' +
                        '\n' +
                        '  {{#each comments}}\n' +
                        '  <h2>By {{fullName author}}</h2>\n' +
                        '  <div class="body">{{body}}</div>\n' +
                        '  {{/each}}\n' +
                        '</div>\n';

        var template = handlebars.compile(source);
        var context  = {
            author: {firstName: "Alan", lastName: "Johnson"},
            body: "I Love Handlebars",
            comments: [{
                author: {firstName: "Yehuda", lastName: "Katz"},
                body: "Me too!"
            }]
        };

        var html    = template(context);
        $.('handlebarDiv').append(html);

    },
 }

The problem in am facing is that i get an error that the function **fullName** is not defined, which means that registering the helper through script tag does not work.
Is there a way this can be done?


Solution

  • You probably need

    imported.src = 'handlebar_helper_load.js';

    with proper path (relative/full)

    instead of

    imported.src = '**handlebar_helper_load.js**';

    because when you append the script tag, browser will request the file, and the file should exist in correct path. Check the network tab in devtools and see if the request succeeds