-2

在以下情况下自动生成模板的最佳方法是什么。

对象组:

Article
  |- Id
  |- Text
Gallery
  |- Id
  |- Type
  |- List<Photos>
Video
  |- Id
  |- VideoHash

所有这些对象都位于var list = new List<dynamic>(). 所以页面包括:

1. article
2. gallery
3. article
4. video

会有这样的对象:

list.Add(Article)
list.Add(Gallery)
list.Add(Article)
list.Add(Video)

现在我的问题是,为特定对象创建模板的最佳方法是什么,然后在生成页面以调用特定模板时,将其与对象数据绑定并作为 .ToString() 发送到浏览器。

是否可以使用.net 或者我必须使用一些模板库?

更新

为了澄清问题,我在问从动态列表为网站生成 HTML 代码的最佳技术、库、组件是什么。

想法是我为文章、视频、画廊创建 HTML 模板,然后我运行页面,它将使用从这个动态列表生成的模板生成整个页面。

4

1 回答 1

1

动态不是类型安全的,也不提供智能感知。在大多数情况下,您应该避免使用它们。改为创建类层次结构

public class Item
{
    public int Id { get; set; }
}

public class Article : Item
{
    public string Text { get; set; }
}

public class Gallery : Item
{
    public string Type { get; set; }
    public List<Photo> Photos { get; set; }
}

public class Video : Item
{
    public string VideoHash { get; set; }
}

现在您可以创建项目列表

var list = new List<Item>();
lst.Add(new Article { Id = 1, Text = "test" });
lst.Add(new Video { Id = 1, VideoHash = "34Rgw^2426@62#$%" });

类用作对象的模板。派生类从基类(这里Id)继承成员。


更新

T4 模板可能看起来像这样

<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" language="C#v3.5" debug="true" hostSpecific="true" #>
<#@ output extension=".html" #>
<#@ Assembly Name="System.dll" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly name="mscorlib.dll" #>
<#@ Assembly name="C:\Users\Oli\Documents\Proj\CySoft\StackOverflowTests\StackOverflowTests\bin\Debug\StackOverflowTests.exe" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="StackOverflowTests.CreateHtmlFromClasses" #>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>Example</h1>
    <table style="Width:100%;">
        <# this.AddProperties(new Article { Id = 77, Text = "The quick brown fox." }); #>
    </table>
</body>
</html>
<#+
    private void AddProperties(object obj)
    {
        Type type = obj.GetType();
        var properties = type.GetProperties();#>
        <tr>
            <td>
                <b><#= type.Name #></b>
            </td>
        </tr>
<#+         foreach (PropertyInfo property in properties) {
#>      <tr>
            <td>
                <#= property.Name #>
            </td>
            <td>
                <#= property.GetValue(obj, null).ToString() #>
            </td>
        </tr>
<#+
        }   
    }
#>

这个例子不是一个真实世界的例子,因为它使用了一个对象的值,因为它只存在于运行时。您只会根据类型进行操作。模板引擎无法访问当前项目的类型。因此,您必须将其放置在另一个项目中。

于 2012-12-21T17:25:32.777 回答