Search code examples
dust.js

Tags within context data in helper


I'm trying to solve for a scenario where data can contain tags that refers to other data. So if my dust file looked like this:

Document.title: {Document.title}
cfg.title: {cfg.title}
output: {#ctx key="{cfg.title}" /}

and my context looks like this:

{
  cfg: {
    title: '{Document.title}'
  }
  , Document: {
    title: 'Here is my title'
  }
  , ctx: function(chunk, context, bodies, params){
    return context.resolve(params.key);
  }
}

I'm getting the following output:

Document.title: This is the title
cfg.title: {Document.title}
output: 

What does my "ctx" helper function need to look like to get it to output "Here is my title"? (note: I know it would be easier to just point to Document.title, but 'cfg' and 'Document' are being generated from different places and are merged at render time)


Solution

  • At some point, you have to compile (or otherwise parse) the minitemplate that forms your config. Here is one possible approach, where I use dust.compile to build the config in advance:

    {
      cfg: {
        title: dust.compile('{Document.title}')
      }, Document: {
        title: 'Here is my title'
      }, ctx: function(chunk, context, bodies, params){
        eval(params.key)(chunk, context);
      }
    }
    

    With the template:

    {#ctx key=cfg.title /}
    

    Note that you are passing cfg.title directly here instead of stringifying it first-- this is important so that you don't have to use context.resolve to do a double-lookup.

    This approach does not generate a template-readable cfg.title, so if that is important to you, you can move the dust.compile step to inside the ctx function.