josh
josh

Reputation: 10318

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.

Upvotes: 4

Views: 2374

Answers (2)

Omeed
Omeed

Reputation: 53

I'm not sure if I agree with the checked answer. There is a much simpler way to change templates, given you know the id of said template. There's a neat function in ractive called 'resetTemplate' which allows you to change templates of a given ractive object. As such:

var rxObject = new Ractive({
  el: '#element',
  template: '#template_1'
});

//what you can do at any point in your code is call ractive.resetTemplate, as such:

rxObject.resetTemplate('#template_2');
<script id="template_1" type="text/html">
  
  //content of this script
  
</script>

<script id="template_2" type="text/html">
  
  //content of this script
  
</script>

I believe it's more complicated and more work doing it the way the 'checked' answer describes.

Upvotes: 3

Rich Harris
Rich Harris

Reputation: 29585

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
  }
});

Upvotes: 7

Related Questions