How to create a showdown.js markdown extension

独自空忆成欢 提交于 2019-12-19 09:44:26

问题


Using the following code, I get working output:

<html>
  <head>
    <script type="text/javascript" src="/js/showdown.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      var converter = new Showdown.converter();
      alert(converter.makeHtml('*test* abc'));
    </script>
  </body>
</html>

Returning <p><em>test</em> abc</p>

I would now like to add an extension. The github page suggests this can be done with:

<script src="src/extensions/twitter.js" />
var converter = new Showdown.converter({ extensions: 'twitter' });

However, modifying my code to:

<html>
  <head>
    <script type="text/javascript" src="/js/showdown.js"></script>
    <script type="text/javascript" src="/js/twitter.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      var converter = new Showdown.converter({ extensions: 'twitter' });
      alert(converter.makeHtml('*test* abc'));
    </script>
  </body>
</html>

Produces the error

"Uncaught Extension 'undefined' could not be loaded.  It was either not found or is not a valid extension."

Adding the following code (as listed under the Filter example)

var demo = function(converter) {
  return [
    // Replace escaped @ symbols
    { type: 'lang', function(text) {
      return text.replace(/\\@/g, '@');
    }}
  ];
}

Produces an error Uncaught SyntaxError: Unexpected token (

I would like to create an extension like this one https://github.com/rennat/python-markdown-oembed to interpret a ![video](youtube_link), but it's unclear how to begin adding this support.


回答1:


In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']});
converter.makeHtml('whatever @meandave2020');
// output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"

I submitted a pull request to update this.




回答2:


The way we write extensions has changed, I found some help with the following filter example : http://codepen.io/tivie/pen/eNqOzP

showdown.extension("example", function() {
  'use strict';
  return [
    {
      type: 'lang',
      filter: function(text, converter, options) {
        var mainRegex = new RegExp("(^[ \t]*:>[ \t]?.+\n(.+\n)*\n*)+", "gm");
        text = text.replace(mainRegex, function(match, content) {
          content = content.replace(/^([ \t]*):>([ \t])?/gm, "");
          var foo = converter.makeHtml(content);
          return '\n<blockquote class="foo">' + foo + '</blockquote>\n';
        });
        return text;
      }
    }
  ]
});


来源:https://stackoverflow.com/questions/20863978/how-to-create-a-showdown-js-markdown-extension

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