Keep correct HTML syntax highlighting in <script> “text/html” templates

核能气质少年 提交于 2019-12-20 02:31:22

问题


Is there a way to retain HTML/ASP.net syntax highlighting and code completion within JavaScript HTML templates inside of razor views?

To help highlight (pun intended) the problem see this image of the problem:

Edit: This questions relates to Visual Studio 2010.


回答1:


Create a helper for it, as shown on Syntax highlighting for script tags with html templates in Visual Studio 2010 MVC3 applications.

Taking the code from there, here are the essentials of what is at that link.

First, add some code to your HtmlHelperExtensions:

public static class HtmlHelperExtensions
{
    public static ScriptTag BeginHtmlTemplate(this HtmlHelper helper, string id)
    {
        return new ScriptTag(helper, "text/html", id);
    }
}

public class ScriptTag : IDisposable
{
    private readonly TextWriter writer;

    private readonly TagBuilder builder;

    public ScriptTag(HtmlHelper helper, string type, string id)
    {
        this.writer = helper.ViewContext.Writer;
        this.builder = new TagBuilder("script");
        this.builder.MergeAttribute("type", type);
        this.builder.MergeAttribute("id", id);
        writer.WriteLine(this.builder.ToString(TagRenderMode.StartTag));
    }

    public void Dispose()
    {
        writer.WriteLine(this.builder.ToString(TagRenderMode.EndTag));
    }
}

Now you can use it like an Html.BeginForm():

@using (Html.BeginHtmlTemplate("person-template"))
{
    <h3>Heading</h3>
    <p>Credits: <span></span></p>
}

Voila! Syntax highlighting by hiding the relevant parts from Visual Studio.




回答2:


It's the "same" solution for WebForms (via here)

(even though the question references MVC/Razor, I got here looking for WebForms)

Helper

In your code-behind .aspx.cs

public string ClientTemplateBegin(string attrId, string attrType = "text/html")
{
    return string.Format(@"<script type=""{0}"" id=""{1}"">", attrType, attrId);
}

public string ClientTemplateEnd()
{
    return "</script>";
}

Usage

In your .aspx file:

<%= ClientTemplateBegin("scriptId", "text/ractive") %>
    <strong>Some Editor</strong>

    {{#each items}}
        Hello {{name}}!  Your age is {{age}}.
    {{/each}}

    <pre>
    {{ json(items) }}
    </pre>
<%= ClientTemplateEnd() %>


来源:https://stackoverflow.com/questions/14449312/keep-correct-html-syntax-highlighting-in-script-text-html-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!