SmartFormat.NET嵌套占位符的List格式错误

时间:2013-11-07 21:49:42

标签: c# .net string-formatting smartformat.net

我正在尝试测试SmartFormat.NET的功能,而我在尝试格式化视图模型项列表时遇到问题。根据{{​​3}},我希望通过嵌套占位符来实现我的目标。

这是我正在使用的模板:

var smartTemplate = @"
<div>This is the title</div>
<div>model name: {Name}</div>
<div>model description: {Description}</div>
<div>model rating: {Rating}</div>
{ItemList:
    <div>{NestedName} has number equal to {Number}</div>
}";

我的观点模型:

public class SimpleTestVM
{
    public string Name { get; set; }
    public string Description { get; set; }
    public int Rating { get; set; }
    public NestedSimpleVM[] ItemList { get; set; } 
}
public class NestedSimpleVM
{
    public string NestedName { get; set; }
    public int Number { get; set; }
}

然后格式化数据我使用几个项目列表初始化视图模型,然后使用以下代码:

Smart.Default.AddExtensions(new ListFormatter(Smart.Default));
Smart.Default.AddExtensions(new ReflectionSource(Smart.Default));
var smartResult = Smart.Format(smartTemplate, model);

在致电Format时,我收到以下错误:

Error parsing format string: Error parsing format string: Could not evaluate the selector "NestedName" at 165
{... includes the template  here...}

深入研究源代码,似乎SmartFormat认为NestedName选择器未被处理,这就是它抛出错误的原因。我无法弄清楚为什么会这样做;据我所知,它正确遵循语法。

1 个答案:

答案 0 :(得分:3)

随着更多的探索来源,我找到了问题。 ListFormatter需要一个“|”字符表示格式化项目的分隔符,因此我将格式更改为:

var smartTemplate = @"
<div>This is the title</div>
<div>model name: {Name}</div>
<div>model description: {Description}</div>
<div>model rating: {Rating}</div>
{ItemList:
    <div>{NestedName} has number equal to {Number}</div> | }
";

这很好用。现在要弄清楚如何根据属性有条件地显示项目。