How can I render dynamic HTML in component?

删除回忆录丶 提交于 2019-12-25 03:43:17

问题


I have the following Ember handlebar template and I want to render it to DOM dynamically including with the onclick event listener. How to do it in EmberJS?

hello.js

export default Ember.Component.extend({
    didInsertElement() {
        var message = `
            <p>Hello World!</p>
            <a onclick={{action "handleOpenUrl"}}>Learn More</a>
        `;
        this.set('message', message);
    },

    actions: {
        handleOpenUrl() {
            //open url code
        }
    }
});

hello.hbs

{{{message}}}

Expected output in DOM

<p>Hello World!</p>
<a>Learn More</a>

And when I click on Learn More, handleOpenUrl should be called


回答1:


You should have something more like this:

hello.js

export default Ember.Component.extend({
   showMessage:false,
   actions: {
        handleOpenUrl() {
            //open url code
        }
    }
});

hello.hbs

{{#if showMessage}}
   <p>Hello World!</p>
   <a {{action "handleOpenUrl"}}>Learn More</a>
{{/if}}

you then toggle showMessage to hide or show your HTML. Your action declaration is also wrong (I've corrected above), see https://guides.emberjs.com/release/templates/actions/

you then consume the component in your main route:

{{hello showMessage=true}}

If you want to render different HTML then you'll need to use yield:

{{#if showMessage}}
   {{yield}}
{{/if}}

this will allow you to consume your component this way:

{{#hello showMessage=true}}
   <p>Hello World!</p>
   <a {{action "handleOpenUrl"}}>Learn More</a>
{{/hello}}

Your action now doesn't live in the component. You'll need the action to be in controller now. TBH I don't see the point in using a component if you want to do this. Just use a standard {{#if}}

It seems that your just trying ot reuse the onclick action. If this is the case then a mixin or a service is the way to go not a component.




回答2:


First your question is wrong: You don't ask if you can render dynamic HTML but if you can render dynamic handlebars! Short answer: no.

Long answer:

Your primary misunderstanding is probably that you think ember is at some point rendering handlebars strings in the browser. It is not! Ember compiles the handlebars to glimmer VM byte code during compile time. The handlebars compiler or the handlebars template will never be sent to the browser. So there is nothing to parse handlebars.

What you want is probably easily achievable but this is a classic X/Y problem situation.

Also be aware that rendering HTML (which is possible) is a security risk. I would recommend you to ask a new question about how to do what you actually want, without focusing on a specific way to solve your problem.



来源:https://stackoverflow.com/questions/54034794/how-can-i-render-dynamic-html-in-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!