Skip to content

Instantly share code, notes, and snippets.

@jamesfoster
Created September 19, 2011 16:20
Show Gist options
  • Save jamesfoster/1226871 to your computer and use it in GitHub Desktop.
Save jamesfoster/1226871 to your computer and use it in GitHub Desktop.
Templated Partials
public static MvcHtmlString TemplatedPartial(this HtmlHelper helper, string partialName, object model, string[] names, params Func<object, HelperResult>[] templates)
{
if (names.Length < templates.Length)
throw new InvalidOperationException("Please provide a name for each template.");
var viewData = new ViewDataDictionary(helper.ViewData);
var templateResults = new Dictionary<string, HelperResult>();
viewData["::PartialTemplates::"] = templateResults;
for (var i = 0; i < templates.Length; i++)
{
templateResults[names[i]] = templates[i](null);
}
return helper.Partial(partialName, model, viewData);
}
public static HelperResult Template(this HtmlHelper helper, string templateName)
{
var templateResults = helper.ViewData["::PartialTemplates::"] as Dictionary<string, HelperResult>;
if (templateResults == null)
throw new InvalidOperationException("No templates exist in the current context.");
return templateResults.ContainsKey(templateName) ? templateResults[templateName] : new HelperResult(t => { });
}
public static bool TemplateExists(this HtmlHelper helper, string templateName)
{
var templateResults = helper.ViewData["::PartialTemplates::"] as Dictionary<string, HelperResult>;
if (templateResults == null)
return false;
return templateResults.ContainsKey(templateName);
}
@{ var test = "Yipee"; }
@Html.TemplatedPartial("Section", new []{"header", "toolbar", "content"},
@<b>Header</b>,
@<i>toolbar</i>,
@<text>this is the content of the box. <div>@test</div></text>)
<div class="section">
<div class="section-heading-container">
<div class="section-heading">
@Html.Template("header")
@if( Html.TemplateExists("toolbar") )
{
<div class="toolbar">
@Html.Template("toolbar")
</div>
}
</div>
</div>
<div class="section-content-container">
<div class="section-content">
@Html.Template("content")
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment