2

我正在尝试测试SmartFormat.NET的功能,但在尝试格式化视图模型项列表时遇到了麻烦。根据这个交流,我想要完成的事情应该可以通过嵌套占位符来实现。

这是我正在使用的模板:

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选择器没有被处理,这就是它抛出错误的原因。我不知道为什么会这样;据我所知,它正确地遵循了语法。

4

1 回答 1

5

通过对源代码的更多探索,我发现了问题所在。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> | }
";

这工作正常。现在要弄清楚如何根据项目的属性有条件地显示项目。

于 2013-11-08T13:21:46.330 回答