使用<yield>标签来包含内部HTML

<yield> 标签是riot的特殊核心功能,可以在运行时将自定义标签的内部模板进行编译和插入,这个技术使你可以用从服务端渲染生成的html内容来扩展你的标签模板

例如使用下面的 riot 标签 my-post

<my-post>
  <h1>{ opts.title }</h1>
  <yield/>
  this.id = 666

</my-post>

你可以在应用中随时包含 <my-post> 标签

<my-post title="What a great title">
  <p id="my-content-{ id }">My beautiful post is just awesome</p>
</my-post>

riot.mount('my-post') 加载后渲染成:

<my-post>
  <h1>What a great title</h1>
  <p id="my-content-666">My beautiful post is just awesome</p>
</my-post>
多点YIELD

>=2.3.12

<yield>标签还支持将模板中不同位置的html内容插入到指定的位置。

例如,使用下面的自定义标签 my-other-post

<my-other-post>
  <article>
    <h1>{ opts.title }</h1>
    <h2><yield from="summary"/></h2>
    <div>
      <yield from="content"/>
    </div>
  </article>
</my-other-post>

在应用中可以这样使用<my-other-post>标签:

<my-other-post title="What a great title">
  <yield to="summary">
    My beautiful post is just awesome
  </yield>
  <yield to="content">
    <p>And the next paragraph describes just how awesome it is</p>
    <p>Very</p>
  </yield>
</my-other-post>

<my-other-post>
  <article>
    <h1>What a great title</h1>
    <h2>My beautiful post is just awesome</h2>
    <div>
      <p>And the next paragraph describes just how awesome it is</p>
      <p>Very</p>
    </div>
  </article>
</my-other-post>
YIELD 与 循环

<yield> 标签可以用在循环中或子标签中,但你必须知道 它总是使用子标签的数据进行解析和编译

看下面的 blog.tag riot 组件

<blog>
  <h1>{ title }</h1>
  <my-post each={ posts }>
    <a href={ this.parent.backToHome }>Back to home</a>
    <div onclick={ this.parent.deleteAllPosts }>Delete all the posts</div>
  </my-post>

  this.backToHome = '/homepage'
  this.title = 'my blog title'

  this.posts = [
    { title: "post 1", description: 'my post description' },
    { title: "post 2", description: 'my post description' }
  ]

  // 本例中需要这个bind来在子标签里也保留父上下文
  deleteAllPosts() {
    this.posts = []

    // 我们需要手动调用 update 函数,因为当前函数由子标签触发,不会自动冒泡到父一级
    this.update()
  }.bind(this)

</blog>

<my-post>
  <h2>{ title }</h2>
  <p>{ description }</p>
  <yield/>
</my-post>

将编译成:


<blog>
  <h1>my blog title</h1>
  <my-post>
      <h2>post 1</h2>
      <p>my post description</p>
      <a href="/homepage">Back to home</a>
      <div>Delete all the posts</div>
  </my-post>
  <my-post>
      <h2>post 2</h2>
      <p>my post description</p>
      <a href="/homepage">Back to home</a>
      <div>Delete all the posts</div>
  </my-post>
</blog>




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值