首页 > 解决方案 > RazorEngineService.RunCompile():当前上下文中不存在名称“section”

问题描述

我有这个子布局试图定义一个部分,@section以在名为_MainLayout.cshtml的主布局中呈现

_SubLayout.cshtml

@{ Layout = "_MainLayout"; }

@section Styles {
     <style>
          .container { width: 50%; }
     </style>
}

<div class="container"></div>

那么这里是预计通过@RenderSection("Styles", false)

_MainLayout.cshtml

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700">
    <style>
        html,
        body {
            margin: 0 !important;
            padding: 0 !important;
            height: 100% !important;
            width: 100% !important;
        }

        @RenderSection("Styles", false)
    </style>
</head>
<html>
<body>
    @RenderBody()
</body>
</html>

但我在编译剃须刀模板时得到了这个RazorEngineService.RunCompile()

private string RenderTemplate<T>(string view, List<string> layouts, T model)
{

    string template = GetTemplate(view);


    var config = new TemplateServiceConfiguration();

    using (var service = RazorEngineService.Create(config))
    {
        if (layouts != null)
            foreach (var layout in layouts)
            {
                var templateLayout = GetTemplate(layout, "Shared");
                if (!string.IsNullOrEmpty(templateLayout))
                    service.AddTemplate(layout, templateLayout);
            }
        
        return service.RunCompile(template, new Guid().ToString(), typeof(T), model);
    };

}

private string GetTemplate(string view, string subFolderName = "")
{
    var root = Directory.GetCurrentDirectory();
    var location = Path.Combine(root, "Views", "Email");

    if(!string.IsNullOrEmpty(subFolderName))
        location = Path.Combine(location, subFolderName);

    var file = Path.Combine(location, view + ".cshtml");

    if (!File.Exists(file))
        return "";

    return File.ReadAllText(file);
}

在此处输入图像描述

标签: c#razorrazorengine

解决方案


推荐阅读