Search code examples
node.jshandlebars.js

How do we use "lookup" in Nodejs to include partials?


We use this syntax to include partial during run time:

{{> (lookup . 'file') }}

file is a var name from the parent file.

I tried to add a prefix to the file name, So I tried:

  • {{> lookup . 'path/file'}}
  • {{> (lookup . (strmerge 'path/' 'file')) }} Note: I made a helper method to merge strings

I tried those and others but nothing worked for me.

Does any one know how to do this?

Thanks


Solution

  • In the code {{> (lookup . 'file') }} we are telling Handlebars that the name of our partial is to be found at the file property of the current context object.

    Assuming a context object like { file: 'myPartial' }, the result of the lookup is {{> myPartial }}, which tells Handlebars to render a partial called "myPartial".

    If we want to add a prefix to our partial, so that Handlebars will register a partial called "path/myPartial", the simplest way to do this would be to add that path to the value of the file property in the context object. The context object would become: { file: 'path/myPartial' }.

    If, for some reason, the "path/" prefix must be added to the template and not the data, then we will need to determine a way to produce the String "path/myPartial" from our current data.

    Both of your attempts put "file" in the name of the property to be looked-up. Your code will try to find the property path/file on the context object and this will fail. We will definitely need a helper to concatenate Strings, but it must concatenate "path/" with the value of file, not the literal String, "file".

    To achieve our goal we will no longer require the lookup helper. The lookup was needed only because you can't write {{> (file) }} in Handlebars, because Handlebars will treat file as a helper instead of as a variable. However, since we are using a concatenation helper, strmerge, we can use the String it returns as our partial name, without any need for a lookup. The correct code becomes:

    {{> (strmerge 'path/' file) }}
    

    It's important to note that file in this example is not in quotes. It is a variable, not a String.

    I have created a fiddle for your reference.