使用Handlebars从动态变量渲染组件

Render a component from a dynamic variable with Handlebars

本文关键字:组件 变量 动态 Handlebars 使用      更新时间:2023-09-26

我想呈现一个将在变量中定义的组件。

我有一个包含类似内容的变量:

page.js

Ember.Controller.extend({
   c: {
      'pageTitle': 'This is the title with a component {{my-component}}'
   }
});

page.hbs

<div>
   {{c.pageTitle}}
</div>

c对象是从内容服务器通过API调用填充的。我想提供从内容中定义的内容注入组件的能力。

基本上,我需要渲染两次,第一次用字符串替换{{pageTitle}},第二次用组件替换{{my-component}}

做这种事的最佳解决方案是什么?

感谢

您可以使用新的{{component}}助手(在Ember的最新版本中)来渲染组件

{{component 'my-component'}}

{{component c.myPageTitleComponent}}

为了呈现文本,您可以做两件事:

在您的模板中

您可以直接在模板中实现文本

{{c.myPageTitleText}} {{component c.myPageTitleComponent}}

使用父零部件

您可以实现一个父组件:

{{my-parent-component text=c.myPageTitleText componentName=c.myPageTitleComponent}}

然后在"我的父组件"中,它看起来像这样:

{{text}} {{component componentName}}

除非您在我的父组件中需要一些自定义逻辑,否则这并没有什么意义。