Skip to content

Added support for partials object #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions jquery.mustache.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,19 +112,44 @@
templateMap = {};
getMustache().clearCache();
}

/**
* Gets partials object (i.e. map {partial name -> actual template content})
* as required by Mustache.
*/
function getPartialsObject(partials) {
var partialsObject = $.extend({}, templateMap);

if (partials !== void 0) {
$.each(partials, function(partialName, templateName) {
if (has(templateName)) {
partialsObject[partialName] = templateMap[templateName];
}
else {
if (options.warnOnMissingTemplates) {
$.error('No template registered for: ' + templateName);
}
partialsObject[partialName] = '';
}
});
}

return partialsObject;
}

/**
* Renders a previously added Mustache template using the supplied templateData object. Note if the supplied
* templateName doesn't exist an empty String will be returned.
*/
function render(templateName, templateData) {
function render(templateName, templateData, partials) {
if (!has(templateName)) {
if (options.warnOnMissingTemplates) {
$.error('No template registered for: ' + templateName);
}
return '';
}
return getMustache().to_html(templateMap[templateName], templateData, templateMap);

return getMustache().to_html(templateMap[templateName], templateData, getPartialsObject(partials));
}

/**
Expand Down Expand Up @@ -184,14 +209,15 @@
* @param templateData One or more JavaScript objects which will be used to render the Mustache
* template.
* @param options.method jQuery method to use when rendering, defaults to 'append'.
* @param partials Optional dynamic partials map which will be used to render the template.
*/
$.fn.mustache = function (templateName, templateData, options) {
$.fn.mustache = function (templateName, templateData, options, partials) {
var settings = $.extend({
method: 'append'
}, options);

var renderTemplate = function (obj, viewModel) {
$(obj)[settings.method](render(templateName, viewModel));
$(obj)[settings.method](render(templateName, viewModel, partials));
};

return this.each(function () {
Expand Down