Embed javascript in markdown

社会主义新天地 提交于 2019-11-29 20:36:57

I had this same problem, but I managed to get JavaScript to appear in my code by putting a newline after the opening tag.

Timothée Boucher

Different solution that might work in some cases: (the selected answer didn't work for me when I was trying to embed a CodePen example)

  • add this to your default layout:

    <!-- Custom JavaScript files set in YAML front matter -->
    {% for js in page.customjs %}
    <script async type="text/javascript" src="{{ js }}"></script>
    {% endfor %}
    
  • In posts where you need some JavaScript files, you can add them in the YAML front matter like so:

    ---
    layout: post
    title: Adding custom JavaScript for a specific post
    category: posts
    customjs:
     - http://code.jquery.com/jquery-1.4.2.min.js
     - http://yourdomain.com/yourscript.js
    ---
    

The async might not be necessary or wanted but you could probably add that as a parameter in customjs. (see YAML front matter for Jekyll and nested lists for details)

Markdown supports inline XHTML but not Javascript.

The example they give on their site shows an empty <script> tag containing a newline. Maybe that's it?

You could use pandoc, which handles this input (and javascript generally) just fine.

I found that escaping the closing '>' symbol in both, the opening and closing 'script' tags, will display it correctly, for example:

  • If you type the follwing:

    <script\>... javascript code...</script\>
    
  • It will be rendered like this:

    <script>... javascript code...</script>
    

That's just my two cents.

To my experience, markdown will outpus javascript text as plain text as long as you remove the code formatting that may confuse markdown.

  1. remove comments from javascript, as /* ... */ is translated to < em>
  2. remove the space indent in the front of each line. < p> may be inserted according to your indentation.

Basically what I do is to review the generated html and find out what extra tags are inserted in between my javascript code by markdown. And remove the formatting that generates the extra tag.

A good idea is to have local and cloud js sources separated:

In the post file:

cloudjs:
 - //cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js
 - //cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js
localjs:
 - datamaps.world.min.js
 - custom.js  

In the default file after footer inclusion:

   {% for js in page.cloudjs %}

        <script type="text/javascript" src="{{ js }}"></script>

    {% endfor %}


    {% for js in page.localjs %}

        <script type="text/javascript" src="{{ "/assets/scripts/" | prepend: site.baseurl | append: js }}"></script>

    {% endfor %}

Just indent the first line contains < script > tag.

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