Skip to content

Commit

Permalink
Support dynamic helper and partials
Browse files Browse the repository at this point in the history
Fixes #46
  • Loading branch information
nolimits4web committed Jan 22, 2018
1 parent 3405dc0 commit d4b937d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import Template7Context from './context';

const Template7Helpers = {
_partial(partialName, options) {
const ctx = this;
const p = Template7Class.partials[partialName];
if (!p || (p && !p.template)) return '';
if (!p.compiled) {
p.compiled = new Template7Class(p.template).compile();
}
const ctx = this;
Object.keys(options.hash).forEach((hashName) => {
ctx[hashName] = options.hash[hashName];
});
Expand Down
9 changes: 7 additions & 2 deletions src/template7-class.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,14 @@ class Template7Class {
} else {
parents = `[${ctx}]`;
}
if (block.helperName in Template7Helpers) {
let dynamicHelper;
if (block.helperName.indexOf('[') === 0) {
block.helperName = getCompileVar(block.helperName.replace(/[[\]]/g, ''), ctx, data);
dynamicHelper = true;
}
if (dynamicHelper || block.helperName in Template7Helpers) {
compiledArguments = getCompiledArguments(block.contextName, ctx, data);
resultString += `r += (Template7Helpers.${block.helperName}).call(${ctx}, ${compiledArguments && (`${compiledArguments}, `)}{hash:${JSON.stringify(block.hash)}, data: ${data} || {}, fn: ${getCompileFn(block, depth + 1)}, inverse: ${getCompileInverse(block, depth + 1)}, root: root, parents: ${parents}});`;
resultString += `r += (Template7Helpers${dynamicHelper ? `[${block.helperName}]` : `.${block.helperName}`}).call(${ctx}, ${compiledArguments && (`${compiledArguments}, `)}{hash:${JSON.stringify(block.hash)}, data: ${data} || {}, fn: ${getCompileFn(block, depth + 1)}, inverse: ${getCompileInverse(block, depth + 1)}, root: root, parents: ${parents}});`;
} else if (block.contextName.length > 0) {
throw new Error(`Template7: Missing helper: "${block.helperName}"`);
} else {
Expand Down
5 changes: 4 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,10 @@ const Template7Utils = {
} else if (block.indexOf(' ') > 0) {
if (isPartial) {
helperName = '_partial';
if (helperContext[0]) helperContext[0] = `"${helperContext[0].replace(/"|'/g, '')}"`;
if (helperContext[0]) {
if (helperContext[0].indexOf('[') === 0) helperContext[0] = helperContext[0].replace(/[[\]]/g, '');
else helperContext[0] = `"${helperContext[0].replace(/"|'/g, '')}"`;
}
}
blocks.push({
type: 'helper',
Expand Down

0 comments on commit d4b937d

Please sign in to comment.