简体   繁体   中英

Is there a way to pass a Handlebars partial (with variables) into another helper?

So there is a template file that is generating a few different layouts for a component in my webpage with different variables dictating sizes and whatnot. So in order to reduce the number of files in the project, I'm trying to reuse the template files for code snippets instead of having dedicated files for them. Through sub expressions, I've had the idea of doing something like this:

{{ escape (template var1=var1 var2=var2 var3=var3) }}

where escape is a helper that takes a string and escapes it (funnily enough), and:

(template var1=var1 var2=var2 var3=var3)

is supposed to have the same effect as {{> template var1=var1 var2=var2 var3=var3 }} , returning complete markup presumably as a string.

The helper doesn't seem to be receiving any string since running typeof on the parameter is returning undefined . I had assumed since {{> template var1=var1 var2=var2 var3=var3 }} is being used higher up in the file, that was registering it for use within the rest of the file, but now I'm thinking that's not how Handlebars does its thing.

Is it possible to retrieve the partial like this or does it need to use the {{> syntax (which doesn't work)?

At the time I asked this question, I was a bit confused with how a context was applied to a partial programmatically. Now that I've done a bit more research (I did try before asking but got nowhere), I now know that Handlebars.compile(partial) will return an object for the given partial and allow a context to be given through partial(context) which should be returned.


Sample Code

function escape(partial) {
    let compiledPartial = Handlebars.compile(partial);

    let context = { greeting: "Hello World!" };

    return compiledPartial(context);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM