Code injection into custom template using handlebars

I am making a custom template and want to include javascript files into the bottom of the page, but I don’t want these files on every page, just the page(s) that uses this template. I know I can do this using the ghost editor at the page level using code injection, but I would rather do it from handlebars as I am little worried that someone will remove my injected code by mistake.

1 Like

In that case I think you could include the script at the end of your template (as you would in the code injection part).

Edit: @GBJsolution is right the block helper with contentFor is the best solution.

Hi you can do that, I have not done it but there is similar thing already in default casper theme.

In casper’s default.hbs file near the bottom you will see following code with comment. don’t miss the triple curly braces.

{{!-- The #block helper will pull in data from the #contentFor other template files. In this case, there's some JavaScript which we only want to use in post.hbs, but it needs to be included down here, after jQuery has already loaded. --}}

{{{block "scripts"}}}

Then see post.hbs file and you will find following code structure.

{{#contentFor "scripts"}}
<script>
// your scripts goes here ...
// this can be used for not only scripts but for any other code block.
</script>
{{/contentFor}}

So, put the {{{block}}} helper in default.hbs file where you want to load the inline script or external script.

Then in your custom template file, wrap that script using {{contentFor}} helper. Make sure the contentFor name ( in example above “scripts” ) match with block name.

3 Likes

Thank you very much. I knew there would a simple way. Worked perfect!

You are most welcome.

BTW, to Ghost team, This helper should be mentioned in documentation where other helpers are listed.

Although It is mentioned in this tutorial
https://ghost.org/tutorials/adding-search-to-a-ghost-theme/#reference-content-blocks-in-your-theme

2 Likes

I agree, Ghost team. I pored through the documentation a few times and searched the forum before finally asking. I should have dug deeper into Casper I suppose.

1 Like

Don’t worry folks, it’s on my list :wink:. The reason it pops up in the tutorial is for this very reason, so I could at least share how this helper works. However you are right, it’s hidden away in a tutorial. The plan is to make these tutorials a bit easier to step through, and to move the contentfor helper info into it’s own theme helper doc :+1:

3 Likes