Search code examples
javascripthandlebars.js

How to escape {{}} in javascript handlebars?


I have the following 'my.txt' file,

Input file

name={{applicationName}}
env=app/{{env}}/{{applicationName}}

I wish to update my text file using javascript handlebars, in such a way that my text file gets updated as,

Expected output

name=myFirstApp
env=app/{{env}}/myFirstApp

I am trying to escape the character "{{env}}", but unfortunately it's not working as expected and instead I'm getting below output,

My output

name=myFirstApp
env=myFirstApp//app

My code looks like below,

readContent = fs.readFileSync(`${__dirname}/../my.txt`, 'utf8')
handlebarsTemplate = Handlebars.compile(readContent)
const output = handlebarsTemplate({
  applicationName: 'myFirstApp'
})
fs.writeFileSync(`newFile.txt`, output, 'utf8')

I am new to this concept. Any help would be appreciated. Thanks!


Solution

  • https://handlebarsjs.com/guide/expressions.html#escaping-handlebars-expressions

    Handlebars content may be escaped in one of two ways, inline escapes or raw block helpers. Inline escapes created by prefixing a mustache block with \. Raw blocks are created using {{{{ mustache braces.

    \{{escaped}}
    {{{{raw}}}}
      {{escaped}}
    {{{{/raw}}}}