【问题标题】:Can NHaml be used as a general purpose template engine? (outside of MVC)NHaml 可以用作通用模板引擎吗? (在 MVC 之外)
【发布时间】:2010-12-08 03:54:58
【问题描述】:

我见过很多人喜欢在 ASP.NET MVC 中使用 NHaml 视图引擎,但我想知道 NHaml 是否可以用作 .NET 中的通用模板引擎?我想从控制台应用程序中使用 NHaml,或者在 ASP MVC 视图引擎环境之外生成 HTML 电子邮件模板。这可能吗?我在任何地方都没有找到很多代码示例来展示如何做到这一点。谢谢!

【问题讨论】:

  • 显然 Razor 中 MVC 3 中的新视图引擎可以在没有 ASP.NET 的情况下独立使用,用于您所描述的事情。因此,这将取决于 NHaml 与 ASP.NET 运行时的松散耦合程度。
  • 如果我的回答没有帮助,请详细说明您的问题。

标签: .net template-engine nhaml


【解决方案1】:

是的,它可以在没有 ASP.Net MVC 的情况下使用。我将它用于我自己的 Web 服务器(但这并不意味着您必须将它与 Web 服务器一起使用)。

在这里查看我如何使用它:http://webserver.codeplex.com/SourceControl/changeset/view/50874#671672

简而言之,您所做的是这样的:

TemplateEngine _templateEngine = new TemplateEngine();

// Add a type used in the template. Needed to that nhaml can find it when compiling the template
_templateEngine.Options.AddReferences(typeof (TypeInYourAssembly));

// base class for all templates
_templateEngine.Options.TemplateBaseType = typeof (BaseClassForTemplates);

//class providing content to the engine, should implement ITemplateContentProvider
_templateEngine.Options.TemplateContentProvider = this; 

// compile the template, 
CompiledTemplate template = _templateEngine.Compile(new List<string> {layoutName, viewPath},
                                                                typeof (TemplateImplementation));

//create a instance
var instance = (NHamlView)template.CreateInstance();

// provide the view data used by the template
instance.ViewData = viewData;

// render it into a text writer
instance.Render(writer);

【讨论】:

  • 不知道,我给了我 1+ 分,因为我直截了当而且很有帮助 :-)
【解决方案2】:

最新的 NHaml 更容易:

    var te = XmlConfigurator.GetTemplateEngine("nhaml.config");

    var ct = te.GetCompiledTemplate(new FileViewSource(new FileInfo("period.nhaml")), typeof(Template));

    var template = ct.CreateTemplate();

    var viewData = new Dictionary<string,object>();

    template.ViewData = viewData;

    template.Render(writer);

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多