官术网_书友最值得收藏!

Block helpers

Block helpers are templates that wrap the content of the block. They can be used to show content in different ways depending on conditions, or they can be used to add extra functionality to the blocks content, for example, some JavaScript calculation on its DOM elements.

In the following example, we will build a simple block helper that will show content based on a Boolean condition.

To do this, we will to add the following code snippet at the end of our example.html file:

<template name="blockHelperExample">
  <div>
    <h1>My Block Helper</h1>
    {{#if this}}
      <p>Content goes here: {{> Template.contentBlock}}</p>
    {{else}}
      <p>Else content here: {{> Template.elseBlock}}</p>
    {{/if}}
  </div>
</template>

The {{> Template.contentBlock}} is a predefined placeholder for the block's content. The same applies for {{> Template.elseBlock}}.

When this (in this example, we use the template's context as a simple Boolean) is true, it will show the given Template.contentBlock. Otherwise, it will show the Template.elseBlock content.

To see how we can use the recently created template as a block helper, take a look at the following example, which we can add to home template:

{{#blockHelperExample true}}
  <span>Some Content</span>
{{else}}
  <span>Some Warning</span>
{{/blockHelperExample}}

Now we should see the following screenshot:

Block helpers

When we now change true, which we pass to {{#blockHelperExample}}, to false, we should see the content after the {{else}} instead.

We can also use a helper function to replace the Boolean value, so that we can switch the block helper dynamically. Additionally, we can pass key-value arguments and access them by their key inside the block helper template, as shown in the following code example:

{{#blockHelperExample myValue=true}}
...
{{/blockHelperExample}}

We can also access the given argument by its name in the block template as follows:

<template name="blockHelperExample">
  <div>
    <h1>My Block Helper</h1>
    {{#if myValue}}
    ...
    {{/if}}
  </div>
</template>

Note

Note that the data context for the block's content will be the one from the template in which the block appears, not the one of the block helper template itself.

Block helpers are a powerful tool because they allow us to write self-contained components that, when packed into a package, can be used as a drop-in-place functionality by others. This feature has the potential to allow for a vibrant marketplace, like the marketplace we see in jQuery plugins.

主站蜘蛛池模板: 大丰市| 齐河县| 滕州市| 治县。| 崇左市| 施甸县| 儋州市| 花莲市| 漳平市| 新巴尔虎右旗| 太仓市| 云南省| 黄龙县| 吉安市| 林芝县| 呼图壁县| 施甸县| 开原市| 枝江市| 赫章县| 永嘉县| 成武县| 肇州县| 蒙山县| 博乐市| 时尚| 南丰县| 绥阳县| 报价| 营口市| 罗山县| 秭归县| 炎陵县| 高邮市| 专栏| 奎屯市| 永仁县| 和林格尔县| 天门市| 延津县| 儋州市|