How to update context in dust helper for chunk.render

我只是一个虾纸丫 提交于 2019-12-11 03:56:51

问题


I am using linkedin's version of dustjs. I want to create a custom helper that updates the context to be more specific for rendering the body of the context.

How can I do that?

Say the context is currently:

{
    title: "News",
    items: [],
    nav: {
       logo: 'logo.png',
       items: []
    },
    body: {
       items: []
    }
}

If I just use chunk.render(bodies.block,context) in my helper, it would be at context level. But I'd like it to render with a scope at the lower 'nav' level:

{
 logo: 'logo.png',
 items: []
}

Somewhat related, is it possible to set the scope/context of the chunk.render call to an object that is higher up?

Say I had been using the array looping helper {#items}{/items} and context inside the loop body is set to each array element, could I write a helper that sets the context for its own body to be higher up and in completely different branch of the object? Like 'body' one?

I know about using {#items:body}, but I am interested in changing scope to different parts of the object based on a key stored in each array element.


回答1:


To render using a selected subset of the context, you can use context.rebase to generate a new context.

This example uses a context helper for succinctness, but you could use a regular Dust helper as well.

Template

{#subcontext key="nav"}
  {#items}{.}{/items}
{/subcontext} 

Context

{
  "subcontext": function(chunk, context, bodies, params) {
    var subcontext = context.get(params.key);
    return chunk.render(bodies.block, context.rebase(subcontext));
  },
  "items": ["Oh", "No"],
  "nav": {
    "items": ["Yay", "Yay"]
  }
}

In response to your second question:

Yes, you can traverse backwards up the context stack. I'll leave this part as an exercise for you, but here's the guidance that you should need:

Your context object in your helper has a property called stack. stack has a property called tail, which is itself an instance of Stack. There's one nested tail for each level of your context, so depending on how you want to do the backwards lookup, you could move anywhere on the stack and then call context.rebase with tail's head to set a different context.



来源:https://stackoverflow.com/questions/28868108/how-to-update-context-in-dust-helper-for-chunk-render

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!