mao*_*o47 2 .net c# string-formatting smartformat.net
我正在尝试测试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>
}";
Run Code Online (Sandbox Code Playgroud)
还有我的视图模型:
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; }
}
Run Code Online (Sandbox Code Playgroud)
然后为了格式化数据,我用一个包含几个项目的列表初始化一个视图模型,然后使用以下代码:
Smart.Default.AddExtensions(new ListFormatter(Smart.Default));
Smart.Default.AddExtensions(new ReflectionSource(Smart.Default));
var smartResult = Smart.Format(smartTemplate, model);
Run Code Online (Sandbox Code Playgroud)
在调用 时Format,我收到以下错误:
Error parsing format string: Error parsing format string: Could not evaluate the selector "NestedName" at 165
{... includes the template here...}
Run Code Online (Sandbox Code Playgroud)
深入研究源代码,似乎 SmartFormat 认为NestedName选择器没有被处理,这就是它抛出错误的原因。我不明白它为什么这样做;据我所知,它正确地遵循了语法。
通过更多的来源,我发现了这个问题。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> | }
";
Run Code Online (Sandbox Code Playgroud)
这工作正常。现在弄清楚如何根据项目的属性有条件地显示项目。