RazorEngineService.RunCompile(): The name 'section' does not exist in the current context

92 Views Asked by At

I have this sub layout trying to define a section via @section to render in a main layout named _MainLayout.cshtml

_SubLayout.cshtml

@{ Layout = "_MainLayout"; }

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

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

then here is where it is expected to be rendered via @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>

but I am getting this while compiling the razor templates via 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);
}

enter image description here

0

There are 0 best solutions below