framework icon indicating copy to clipboard operation
framework copied to clipboard

Markdown (md) tagged template literal

Open mbostock opened this issue 2 years ago • 2 comments

Here’s a possible implementation:

```js
import markdownit from "npm:markdown-it";
```

```js
const Markdown = new markdownit({html: true});

function md(strings) {
  let string = strings[0];
  for (let i = 1; i < arguments.length; ++i) {
    string += String(arguments[i]);
    string += strings[i];
  }
  const template = document.createElement("template");
  template.innerHTML = Markdown.render(string);
  return template.content.cloneNode(true);
}
```

```js
md`# Hello, ${"world"}!`
```

We don’t currently do this because it’s unsafe — if you interpolate text into the Markdown, it’s interpreted as Markdown or HTML and can affect the meaning of statically declared content (unlike Hypertext Literal, which is safe). Perhaps another option would be to offer an md.unsafe function that makes the unsafe-ness more obvious and could allow us to offer a safe md tagged template literal in the future.

```js
import markdownit from "npm:markdown-it";
```

```js
const Markdown = new markdownit({html: true});

const md = {
  unsafe(string) {
    const template = document.createElement("template");
    template.innerHTML = Markdown.render(string);
    return template.content.cloneNode(true);
  }
};
```

```js
md.unsafe(`# Hello, ${"world"}!`)
```

mbostock avatar Feb 22 '24 12:02 mbostock

Any updates to this? I am trying to implemented a nested table which works fine as html file. I have developed helper functions to duplicate it but unfortunately, I am not able to implement using

const container = document.createElement('div');
container.innerHTML = generateNestedTable(data);
document.body.appendChild(container);

Any suggestions on how to do this? Thanks! Gani -

gganapat avatar Mar 27 '25 20:03 gganapat

Any updates to this? I am trying to implemented a nested table which works fine as html file. I have developed helper functions to duplicate it but unfortunately, I am not able to implement using

const container = document.createElement('div');
container.innerHTML = generateNestedTable(data);
document.body.appendChild(container);

Any suggestions on how to do this? Thanks! Gani -

Never mind. I found a hint in this link

gganapat avatar Mar 27 '25 21:03 gganapat