【问题标题】:SmartFormat.NET nested placeholders in List format error列表格式错误中的 SmartFormat.NET 嵌套占位符
【发布时间】:2013-11-07 21:49:42
【问题描述】:

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

这是我正在使用的模板:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多