Prepending/appending Razor views and sections with

2019-04-11 13:03发布

My razor views are stored in a database and provided to the site via a VirtualPathProvider. Given certain flags, the service which returns them will, for debugging purposes, demarcate the beginning and end of each view with HTML comments including extra debugging information (caching, versioning, authorship, etc.) When using layouts, only the outermost layout view will include this information; in child layouts/views, the HTML comments including the information are not in a @section so never make it to the response. I'd want these comments to appear before the first rendered section, at least, but before and after each rendered section would be great.

I wonder if there's a clean way to do this anyone can think of or has had success with. If it matters, I'm using a custom view base type, so can override any relevant methods, and I'm willing to override the view engine.

What I currently see:

<!-- start of 'layout1' -->
entire html response
<!-- end of 'layout1' -->

What I'd optimally like to see:

<!-- start of 'layout1' -->
<html>
  <body>
    <!-- start of 'layout2' section 'section1' -->
      <div id="header">
        <!-- start of 'view1' section 'section2' -->
          <h1>hello!</h1>
        <!-- end of 'view1' section 'section2' -->
      </div>
    <!-- end of 'layout2' section 'section1' -->
  </body>
</html>
<!-- end of 'layout1' -->

2条回答
beautiful°
2楼-- · 2019-04-11 13:36

If I'm following you correctly, you just need those comments added at the beginning and end of each view? That's pretty simple if your custom view base is inheriting from WebViewPage.

public class MyViewBase<T> : WebViewPage<T> 
{
    public override void ExecutePageHierarchy()
    {
        WriteLiteral("<!-- Started Layout -->");
        base.ExecutePageHierarchy();
        WriteLiteral("<!-- Ended Layout -->");
    }
}

Note that this will get kinda noisy if you have various editor or display templates that all use the same custom base class.

查看更多
登录 后发表回答