Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active August 15, 2024 15:16
Show Gist options
  • Save jorendorff/d3df45120ef8e4a342e5 to your computer and use it in GitHub Desktop.
Save jorendorff/d3df45120ef8e4a342e5 to your computer and use it in GitHub Desktop.

Writing template strings in Markdown

With template strings coming to ES6, the backtick (`) means something in Markdown and in JavaScript. If you write this:

To display a message, write `alert(`hello world!`)`.

it'll render like this:

To display a message, write alert(hello world!).

So how can you mix ES6 template strings with Markdown?

Use double backticks

Markdown has always supported using multiple backticks as code delimiters. If you use two, or three, or four backticks to start a snippet of code, then any shorter sequences of backticks within that snippet are shown verbatim in the output.

For example, if you want the output to look like this: alert(`${color} alert!`)

just type: ``alert(`${color} alert!`)``

(In order to make the previous line look like that, I had to use triple-backticks. View source.)

Fenced code blocks are fine

In Github Flavored Markdown fenced code blocks, you don't have to do anything special at all. Template strings don't cause any problems there, though Github's syntax highlighting library doesn't seem to recognize them yet.

This Markdown:

```javascript
var headline = `${greetings}, ${location}${enthusiasm_level}`;
$("#post").html`
  <h1>${headline}</h1>
  ${body}
`;
```

looks like this:

var headline = `${greetings}, ${location}${enthusiasm_level}`;
$("#post").html`
  <h1>${headline}</h1>
  ${body}
`;
@Becavalier
Copy link

Awesome!

@szxmsu
Copy link

szxmsu commented Oct 25, 2016

Awesome!

@realgeoffrey
Copy link

Wonderful

@Powell-v2
Copy link

Thanks for the tip!

@FlameWolf
Copy link

But the double-tick approach will not work if you want to wrap an entire template string inside them, like this: ​`Sum: ${a + b}`​.

So how did I just do that? The trick is to use triple backticks and a Zero-Width Space character. Example: ``[ZWS]`Sum: ${a + b}`[ZWS]``.

GitHub's editor will display the ZWS characters as red dots, so they'll be easy to locate and edit.

@dengshenkk
Copy link

alert(`${color} alert!`)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment