Sublime Text 2 recognize underscore templates as H

2019-01-30 02:16发布

问题:

So, i'm using underscore.js templates, in which i have to put my html template inside a script tag, like this

<script id="contactTemplate" type="text/template">
    <img src="{{ photo }}" alt="{{ name }}" />
    <h1>{{ name }}<span>{{ type }}</span></h1>
    <div>{{ address }}</div>
    <dl>
        <dt>Tel:</dt><dd>{{ tel }}</dd>
        <dt>Email:</dt><dd><a href="mailto:{{ email }}">{{ email }}</a></dd>
    </dl>
</script>

but sublime text 2 is evaluating the code inside as regular js, how can i change that?

Thanks in advance!

回答1:

  1. Go to "Browse Packages" in the menu (where the menu item is depends on your platform).
  2. Open up HTML/HTML.tmLanguage
  3. Change this line (line 286 in my HTML.tmLanguage):

    <string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)</string>

    to this:

    <string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)(?!.*type=["']text/template['"])</string>

Now any script tags with type="text/template" or type='text/template' will render as html and not javascript.



回答2:

Because modifying built-in packages isn't exactly easy, safe, or portable (especially in ST3), I split out Matt York's change into its own package.

It is available via Package Control, and supports both Sublime Text 2 and 3 on all platforms.

HTML Underscore Syntax



回答3:

For those of us using Sublime Text 3

I thought I'd consolidate the information into something easier to find, since none of the answers or comments directly gave me the solution I needed. Matt York's answer is mostly correct, but Shane N's solution is a bit more flexible:

<string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)(?!.*type=["']text/(temp‌​late|html)['"])</string>

You can find HTML.sublime-package inside C:\Program Files\Sublime Text 3\Packages, as mentioned by PAEz.

Instructions

  1. Extract HTML.sublime-package's contents like any normal zip file
  2. Inside the new /HTML directory you just created, open HTML.tmLanguage and modify the line mentioned above (probably line 286)
    1. It should come right after <key>begin</key>
  3. Save your changes, then add the /HTML directory that HTML.tmLanguage lives in to a new zip file
  4. Delete the old HTML.sublime-package file
  5. Change the filetype from .zip to .sublime-package (make sure Sublime isn't running while you do this)
  6. You should now be good to go - fire up Sublime and check out your awesome newly-highlighted templates!


回答4:

For those of us using Sublime Text 3 use the plugin "PackageResourceViewer" to edit HTML.sublime-package

PackageResourceViewer