This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Hogan = require('./twitter-hogan'); | |
var renderOptions = { asString: true, sectionTags: [{ o: '_i', c: 'i' }] }; | |
var translateMustache = require('./translate-mustache'); | |
function extractPartials(tmpl) { | |
// need eval to pull the partials out of the Hogan-generated string | |
/* eslint-disable no-eval */ | |
var hoganParams = eval(`(${tmpl})`); | |
/* eslint-enable no-eval */ | |
var partialNames = []; | |
for (var key in hoganParams.partials) { | |
partialNames.push(hoganParams.partials[key].name); | |
} | |
return partialNames; | |
} | |
// templates/client is specified in resolve.config | |
function partialPath(name) { | |
return `${name}.mustache`; | |
} | |
function templateModuleWithoutPartials(tmpl) { | |
return `module.exports = new Hogan.Template(${tmpl});`; | |
} | |
function templateModuleWithPartials(tmpl, partialNames) { | |
var dependencies = partialNames.map((name) => | |
`'${name}': require('${partialPath(name)}')` | |
).join(',\n'); | |
// Hogan is injected by ProvidePlugin | |
return ` | |
var mergeTemplates = require('app/utils/merge_templates'); | |
var dependencies = { | |
${dependencies} | |
}; | |
var defaultPartials = mergeTemplates(dependencies); | |
var template = new Hogan.Template(${tmpl}); | |
function render(context, partials, indent) { | |
partials = partials || {}; | |
for (var key in defaultPartials) { | |
if (!partials[key]) { | |
partials[key] = defaultPartials[key]; | |
} | |
} | |
return template.render(context, partials, indent); | |
}; | |
module.exports = { | |
template: template, | |
partials: defaultPartials, | |
render: render | |
} | |
`; | |
} | |
module.exports = function(source) { | |
var phrases = this.options.phrases || {}; | |
this.cacheable(); | |
var translatedSource = translateMustache(source, phrases); | |
var tmpl = Hogan.compile(translatedSource, renderOptions); | |
var partialNames = extractPartials(tmpl); | |
if (!partialNames.length) { | |
return templateModuleWithoutPartials(tmpl); | |
} else { | |
return templateModuleWithPartials(tmpl, partialNames); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment