简体   繁体   English

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

[英]Render a component from a dynamic variable with Handlebars

I'd like to render a component that I will define within a variable. 我想渲染一个我将在变量中定义的组件。

I have a variable containing content like that: 我有一个包含这样的内容的变量:

page.js page.js

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

page.hbs page.hbs

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

The c object is populated from an API call, from a content server. 从内容服务器的API调用填充c对象。 I would like to provide the capability to inject components from what is defined in the content. 我想提供从内容中定义的内容注入组件的功能。

Basically what I need would be to render 2 times, the first time to replace my {{pageTitle}} with the string, and the second time to replace {{my-component}} with the component. 基本上我需要渲染2次,第一次用字符串替换{{pageTitle}} ,第二次用{{my-component}}替换{{my-component}}

What would be the best solution to do such a thing? 做这样的事情的最佳解决方案是什么?

Thanks 谢谢

You could render the component using the new {{component}} helper (in the latest version of Ember) 您可以使用新的{{component}}帮助程序(在最新版本的Ember中)渲染组件

{{component 'my-component'}}

{{component c.myPageTitleComponent}}

For the text to be present, you could do two things: 对于要出现的文本,您可以做两件事:

In your Template 在你的模板中

You could implement the text directly in your template 您可以直接在模板中实现文本

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

Using a Parent Component 使用父组件

You could implement a parent component: 您可以实现父组件:

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

Then in 'my-parent-component', it would look like this: 然后在'my-parent-component'中,它看起来像这样:

{{text}} {{component componentName}}

This doesn't really make sense though unless you needed some custom logic in my-parent-component. 除非你在my-parent-component中需要一些自定义逻辑,否则这并没有多大意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM