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 @ 2024-07-09 15:31  microsoft-zhcn  阅读(4)  评论(0编辑  收藏  举报