Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing (or "optional") expressions in handlebars.js?

I'm writing a build script in node. In a nutshell, the script does the following:

  • prompts the user for information (project name, description, etc)
  • clones a template git repo
  • renames files from their template name (e.g. com_foo_template.js --> com_foo_myproject.js)
  • replaces tokens in the some template files based on the input in step 1

I'm attempting to use Handlebars.js for the token replacement step.

There's a second phase for deploying, which also involves token substitution. This is the root of my question.

In some of the files, all of the tokens contained within will be replaced during init-time (the clone/rename/replace part). In other files, only some of these tokens will be replaced at init-time, and others won't be replaced until the deploy step runs (things like the deploy date, the git commit hash, etc.). Consider the following file:

<zimletConfig name="{{name}}" version="{{deploy_version}}">
  <global>
    <property name="allowedDomains">*.foo.com</property>
    <property name="gitCommit">{{gitcommit}}</property>
    <property name="deployDate">{{deploydate}}</property>
  </global>
</zimletConfig>

In this file, only {{name}} should be replaced at init-time; the other tokens should be replaced at deploy-time only. When I run my init step, though, the deploy-time tokens are replaced with empty strings:

<zimletConfig name="com_foo_myproject" version="">
  <global>
    <property name="allowedDomains">*.foo.com</property>
    <property name="gitCommit"></property>
    <property name="deployDate"></property>
  </global>
</zimletConfig>

Is there a way to have handlebars not replace tokens if they don't exist in the object passed in?

like image 514
grahamb Avatar asked Nov 05 '22 07:11

grahamb


1 Answers

I think I've got a solution; I implemented a helperMissing helper and it seems to work like I'd think it should.

handlebars.registerHelper('helperMissing', function(token) {
    return '{{'+token+'}}';

});

I'm curious if this is the best way to solve the problem.

like image 71
grahamb Avatar answered Nov 09 '22 14:11

grahamb