开发者

How do I render a collection of objects with Nustache?

I'm attempting to use Nustache so that I can share rendering templates between back end and front end code in an ASP.Net web app. It's working fine when I just pass an object to a template, but I can't figure out how to get it to render a collection. So if I have a template like this:

{{#RenderItems}}
  <th data-warning="{{WarningLevel}}" data-limit="{{LimitLevel}}">{{TotalHours}}</th>
{{/RenderItems}}

Then I want to pass in a collection of objects and get out a set of th elements.

Things I've tried:

  • Creating a class with the properties WarningLevel, LimitLevel and TotalHours, adding objects to a List and passing that directly: Nustache.Core.Render.FileToString(System.Web.HttpContext.Current.Server.MapPath("my.template"), ListOfObjects)
  • Doing the same thing, except creating an anonymous class: Nustache.Core.Render.FileToString(System.Web.HttpContext.Current.Server.MapPath("my.template"), new { Rende开发者_JS百科rItems = ListOfObjects})
  • Instead of a list, using a Dictionary containing the same objects
  • Using a dictionary of dictionaries - so each item is itself a dictionary with the properties named above

The only way it renders anything at all is if I use an anonymous class, but I can't get it to populate the template with the named items whatever I do. I'm sure I'm missing something fairly obvious here, as I assume this should be straightforward, but the documentation says 'look in the code and the tests' but I can't work out which test is actually dealing with this scenario. Can someone either point me in the right direction, or provide some example code?


I was able to get this working with the following class and controller action:

public class Person {
    public string Name { get; set; }
    public string Email { get; set; }
}

public ActionResult Index() {
    var people = new List<Person>() { 
        new Person { Name = "Albert Adams", Email = "albert@email.com" },
        new Person { Name = "Bob Becker", Email = "bob@email.com" },
        new Person { Name = "Charles Charles", Email = "charles@email.com" }
    };

    ViewData["People"] = people;

    ViewResult viewResult = View();
    viewResult.ViewEngineCollection = new ViewEngineCollection { new NustacheViewEngine() };

    return viewResult;
}

And then Index.nustache:

{{#People}}
    <p>{{Name}} - {{Email}}</p>
{{/People}}

Note that I pulled the latest changes from the Nustache repo this morning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜