CodeMirror HTML mode not working

前端 未结 2 1489
闹比i
闹比i 2020-12-30 20:44

I\'m trying to style code samples with CodeMirror, but it works partially - it applies the selected theme to the textarea but the syntax is not highlighted.

相关标签:
2条回答
  • 2020-12-30 21:13

    Just in case if my experience can be helpful to someone.

    I did following mistake:

    <script src="lib/codemirror.js"></script>
    <script type="text/javascript">
        const editor = CodeMirror.fromTextArea(document.getElementById('textarea'), {
            mode: "css",
            lineNumbers: true,
            foldGutter: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
            lint: true
        });
    </script>
    <script src="addons/lint/lint.js"></script>
    <script src="addons/lint/css-lint.js"></script>
    <script src="addons/fold/brace-fold.js"></script>
    <script src="addons/fold/foldcode.js"></script>
    <script src="addons/fold/foldgutter.js"></script>
    <script src="addons/fold/indent-fold.js"></script>
    <script src="addons/fold/markdown-fold.js"></script>
    <script src="mode/css.js"></script>
    <script src="//unpkg.com/csslint@1.0.5/dist/csslint.js"></script>
    

    This is wrong: I called first codemirror.js - main file, then initialized Editor and later called its assets. In this case it didn't work and it took time for me to find the issue (I was doing it in WordPress so I just made my script depend on codemirror.js only).

    0 讨论(0)
  • 2020-12-30 21:28

    CodeMirror parses HTML using the XML mode. To use it, the appropriate script must be included, same as with any other mode.

    Add its dependency in your markup:

    <script type="text/javascript" 
            src="/site.com/js/libs/codemirror/mode/xml/xml.js"></script>
    

    and set the mode to xml:

    config = {
        mode : "xml",
        // ...
    };
    

    In addition, you may want to configure the parser to allow for non well-formed XML. You can do so by switching the htmlMode flag on:

    config = {
        mode : "xml",
        htmlMode: true,
        // ...
    };
    

    See the XML/HTML mode demo for a live example.

    0 讨论(0)
提交回复
热议问题