NetCore 模板引擎

NuGet 导入:RazorEngine.NetCore

 

HTML模板

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>@Model.Title</title>
</head>
<body>
    <h1>@Model.Title</h1>
    <p>作者:@Model.Author - 发布时间:@Model.CreateDate</p>
    <p>@Raw(Model.Content)</p>
</body>
</html>

 Model 层(ArticleModel.cs)

public class ArticleModel
{
    /// <summary>
    /// 文章ID
    /// </summary>
    public int Id { get; set; }
    /// <summary>
    /// 文章标题
    /// </summary>
    public string Title { get; set; }
    /// <summary>
    /// 文章内容
    /// </summary>
    public string Content { get; set; }
    /// <summary>
    /// 作者
    /// </summary>
    public string Author { get; set; }
    /// <summary>
    /// 发布时间
    /// </summary>
    public DateTime CreateDate { get; set; }
}

 

View层(C# 程序)

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IWebHostEnvironment _env;
    public IndexModel(ILogger<IndexModel> logger, IWebHostEnvironment env)
    {
        _logger = logger;
        _env = env;
    }
 
    public void OnGet()
    {
        //模板路径
        string filePath = $"{_env.WebRootPath}\\templates\\default\\index.html";
        // 读取模板
        string template = System.IO.File.ReadAllText(filePath);
        //添加模板
        Engine.Razor.AddTemplate("index.cshtml", template);
        //编译模板
        Engine.Razor.Compile("index.cshtml", null);
        //执行模板
        ViewData["Run"] = Engine.Razor.Run("index.cshtml", null, new ArticleModel() { Title = "标题", Author = "作者", Content = "内容测试" });
    }
}

 

View层(shtml 代码)

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
 
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    @Html.Raw(ViewData["Run"])
</div>

 

项目目录如下:WebRazor.zip

 

posted @   microsoft-zhcn  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示