Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

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

This comment has been minimized.

Copy link

commented Jun 8, 2016

Awesome!

@chnhyg

This comment has been minimized.

Copy link

commented Oct 25, 2016

Awesome!

@realgeoffrey

This comment has been minimized.

Copy link

commented May 24, 2017

Wonderful

@Powell-v2

This comment has been minimized.

Copy link

commented Jan 17, 2018

Thanks for the tip!

@FlameWolf

This comment has been minimized.

Copy link

commented May 8, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.