ractivejs component nesting

2019-08-09 15:32发布

问题:

The documentation seems to indicate that it is possible to nest custom components within other custom components (http://docs.ractivejs.org/latest/components) :

<Foo on-Bar.foo="barfooed" on-Baz.*="baz-event" on-*.bippy="any-bippy">
  <Bar /><Baz /><Baz />
</Foo>

However, the following code only displays the tooltip. The inner custom components al-tt-translation, and al-tt-input are not initialized. In fact, replacing those two components by a string do not lead to that string being passed in anyway to the tooltip custom component .

tooltip = new Ractive({
    el: 'airlang-rdt-tt-container',
    template: "" +
        "<al-tooltip>"+
        "    <al-tt-translation display='{{display_translation}}' translation_lemma='{{translation_lemma}}' result_rows='{{result_rows}}'/> " +
        "    <al-tt-input/> "+
        "</al-tooltip>",
    append: true,
    components : {
        'al-tooltip': Component_Tooltip,
        'al-tt-translation' : Component_TT_Translation,
        'al-tt-input' : Component_TT_Input
    },
    data : {
        display_translation : 'block',
        translation_lemma : 'example'
    }
});

Should I conclude that it is not possible to use the custom tags in the same way than regular HTML tags?

Note : From the documentation, I understand that there is something to do with {{>content}} or {{>yield}} but I can't seem to make it work. What is the right way to do this?

回答1:

For your example, your <al-tooltip> template needs to have either a {{yield}} or {{>content}} somewhere in it to direct where the contained content should go.

Simple example of how it works:

var Outer = Ractive.extend({ template: '<div>{{yield}}</div>' });
var Inner = Ractive.extend({ template: '<span>hello world</span>' });

var ractive = new Ractive({
    el: document.body,
    template: '<outer><inner/><inner/></outer>'
    components: {
        outer: Outer,
        inner: Inner
    }
})

produces:

<div><span>hello world</span><span>hello world</span></div>

{{yield}} means that the content still runs in the context in which it originated, {{>content}} means import the content as a partial and run it. In your example it probably won't matter because you're using components and not raw templates.