This is an open source plug-in I wrote for a project at Behance to make loading partials easier

In template:

{{>templates/someDir/someTemplate}}

In Ractive code:

define(['ractive-partials!template'], function() {
    /* code that does things to save the world */
});

Notice how we didn’t import someTemplate from our Javascript.

Try it out:

bower install ractive-partials

More usage instructions are available at the GitHub page.

How it works


The bulk of the plug-in’s work is accomplished via the following regex:

/{{>\s?([^\s]+?)\s?}}/gi

See how it works here.

This regex is run against a Mustache/Ractive template, and returns each partial that has a slash in it. Because slashes are treated as expressions, we have to use a different character. By default, the slash is re-written as ‘$’.

Now that we have valid partial names, we do the following

  • Get the partial template with the RequireJS text plug-in
  • Parse the partial template through ractive-partials (recursive)
  • For every partial we found with slashes, put them on the global Ractive.partials object. By doing so, we get this:

In template:

{{>path$someTemplate}}

On global Ractive object:

Ractive.partials.path$someTemplate

Check out the code (written in ES6!) here

Note: The regex above includes a minor bug fix that is not published at the time of writing. There was a bug where something that looked like this would break

{{#someCondition}}{{>path/someTemplate}}{{/someCondition}}

The original regex was this

/{{>\s?([^\s]+)\s?}}/gi

Notice the missing ‘+?’ in ‘([^\s]+)’. This matches the fewest number of characters possible rather than the max. Try changing to the old regex and seeing the difference in the regex tester.

Enjoy!