Keep correct HTML syntax highlighting in [removed]

2020-04-11 15:56发布

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: enter image description here

Edit: This questions relates to Visual Studio 2010.

2条回答
forever°为你锁心
2楼-- · 2020-04-11 16:05

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() %>
查看更多
别忘想泡老子
3楼-- · 2020-04-11 16:11

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.

查看更多
登录 后发表回答