Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 749
Victor Avatar asked Nov 19 '25 17:11

Victor


2 Answers

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.

like image 95
Anthony Mills Avatar answered Nov 22 '25 19:11

Anthony Mills


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() %>
like image 33
drzaus Avatar answered Nov 22 '25 19:11

drzaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!