问题
Is it possible to have a template with html content in vm for a block component?
I'm doing a lot of stuff in html, and want the html reside in a .vm, not in codebehind.
Here is what i've got:
public class TwoColumn : ViewComponent
{
public override void Render()
{
RenderText(@"
<div class='twoColumnLayout'>
<div class='columnOne'>");
// Context.RenderBody();
Context.RenderSection("columnOne");
RenderText(@"
</div>
<div class='columnTwo'>");
Context.RenderSection("columnTwo");
RenderText(@"
</div>
</div>
");
}
}
Here is what i want to get: pageWithTwoColumns.vm:
#blockcomponent(TwoColumn)
#columnOne
One
#end
#columnTwo
Two
#end
#end
twocolumn/default.vm (pseudocode):
<div class="twoColumnLayout">
<div class="columnOne">
#reference-to-columnOne
</div>
<div class="columnTwo">
#reference-to-columnTwo
</div>
</div>
回答1:
You have the RenderView
method on the base class of the ViewComponent. what you can do is use the overload that writes the view in-place into a TextWriter.
just stick this method in your viewcomponent and you should be done
string RenderViewInPlace(string viewTemplate)
{
var buffer = new StringBuilder();
using (var writer = new StringWriter(buffer))
{
RenderView("myview", writer);
return buffer.ToString();
}
}
回答2:
I have finally found a solution using Ken's suggested StringWriter technique, but with different method. It's not RenderView, it's RenderSection
public override void Render()
{
PropertyBag["sectionOneText"] = RenderSectionInPlace("sectionOne");
PropertyBag["sectionTwoText"] = RenderSectionInPlace("sectionTwo");
base.Render();
}
public string RenderSectionInPlace(string sectionName)
{
var stringBuilder = new StringBuilder();
Context.RenderSection(sectionName, new StringWriter(stringBuilder));
return stringBuilder.ToString();
}
template:
<div class="twoColumnLayout">
<div class="columnOne">
$sectionOneText
</div>
<div class="columnTwo">
$sectionTwoText
</div>
</div>
I would suggest a feature for monorail, if you don't mind. It would be great to be able to reference the section from view template like this:
#render(sectionOne)
来源:https://stackoverflow.com/questions/2773529/template-in-monorail-viewcomponent