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

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.

主站蜘蛛池模板: 沭阳县| 紫云| 紫阳县| 伊金霍洛旗| 株洲市| 黄大仙区| 祥云县| 元阳县| 桓台县| 平湖市| 新竹县| 合江县| 清流县| 互助| 年辖:市辖区| 富民县| 嵊州市| 汽车| 大竹县| 陆丰市| 河北区| 横峰县| 巴林右旗| 丹阳市| 玉树县| 荣成市| 海晏县| 徐水县| 栖霞市| 黄梅县| 志丹县| 兴隆县| 都昌县| 梧州市| 桂平市| 海晏县| 德江县| 新化县| 巴彦淖尔市| 鹿泉市| 屏东市|