Search code examples
ractivejs

Components inside partials


How can Ractive Components live inside partials?

I have a FormInput Component

<FormInput type="text" label="Please enter name" value="{{John Doe}}"/>

which translates to

<div>
  {{label}}: <input type="{{type}}" value="{{value}}">
</div>

There is also another component Modal

<div>
  {{>modalContents}}
</div>

When I create a Modal component with

modalContents:'<FormInput type="text" label="Please enter name" value="{{John Doe}}"/>'

the component isn't rendered at all, probably because ractive thinks it is just text. I know, I am missing something here... Is there a way to make it actually parse the component?

*Note: examples are simplified


Solution

  • This does work, but you need to make sure that the FormInput component is registered. One way is to register it globally...

    Ractive.components.FormInput = FormInput;
    

    ...but you can also register it when creating a new instance:

    var FormInput = Ractive.extend({
      template: '<div>{{label}}: <input type="{{type}}" value="{{value}}"></div>'
    });
    
    var Modal = Ractive.extend({
      template: '<div>{{>modalContents}}</div>'
    });
    
    var modal = new Modal({
      el: 'body',
      partials: {
        modalContents: '<FormInput type="text" label="Please enter name" value="John Doe"/>'
      },
    
      // register the component here
      components: { FormInput: FormInput }
    });
    

    There is a small syntax error in your example which may be relevant – it should be John Doe, not {{John Doe}}.

    Demo here: http://jsfiddle.net/rich_harris/80w8o1bu/