Search code examples
javascriptjavascript-marked

How to store use triple-quoted backtick strings with marked.js


I'm using marked.js to render code that we want to store (ultimately as JSON). However, the I can't get triple-back-ticked convention to render correctly. I'm sure user error on my part but how would I to get the following to work?

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div id="content"></div>
<script>
let str = marked.parse("here is the body of arguments ```\n\nclass User\n  def say_my_name\n  puts 'my name'\n  end\nend```");
document.getElementById('content').innerHTML = str;
</script>

which renders for me like:

enter image description here


Solution

  • What you have is

    here is the body of arguments ```
    
    class User
      def say_my_name
      puts 'my name'
      end
    end```
    

    But that is not valid. The code fences should always be on a new line:

    let str = marked.parse("here is the body of arguments \n```\n\nclass User\n  def say_my_name\n  puts 'my name'\n  end\nend\n```");
    document.getElementById('content').innerHTML = str;
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <div id="content"></div>