views:

36

answers:

2

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  A: 

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();
    }           
}
Ken Egozi
Sorry, this is not quite what i was up to. What i'm looking for, is a method to render a named section from within the template, something like: <div>$RenderSectionHere("columnOne")</div>
George Polevoy
A: 

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)
George Polevoy
cool.Now that Monorail is on github, it is simply a matter of fork+feature+pull request :)
Ken Egozi