Search code examples
templatesractivejs

How to handle multiple templates in Ractive


Let's say I have two templates: An index template with my main content, and a changelog template with the changelog. They are considered different templates:

<script id='index' type='text/ractive'>
// ...
</script>

<script id='changelog' type='text/ractive'>
// ...
</script>

ractive = new Ractive({...});

What would be the best way to be able to change between these templates on the fly and programmatically? I was thinking that I could change the template variable for the Ractive instance, i.e. ractive.template = '#changelog'; but changing that doesn't update the output content. Ideally, I'd like it so that a user could click a button in a menu and switch between index and changelog.


Solution

  • Changing templates dynamically is something that we're looking at for a future release - see this GitHub thread for some background.

    At present, the best way to achieve this would be something like this:

    <script id='main' type='text/ractive'>
      {{# page === 'index' }}
        {{>index}}
      {{/}}
    
      {{# page === 'changelog' }}
        {{>changelog}}
      {{/}}
    </script>
    
    <script id='index' type='text/ractive>...</script>
    <script id='changelog' type='text/ractive>...</script>
    

    Then, inside your app, ractive.set('page', 'changelog') to hide the index template and display the changelog.

    If you wanted to do this without having loads of <script> tags, you'd set the options like this:

    ractive = new Ractive({
      /* other options... */
      template: mainTemplate,
      partials: {
        index: indexTemplate,
        changelog: changelogTemplate
      }
    });