Skip to content

Commit b8f9d15

Browse files
authored
Add example on how to inject raw HTML
Closes GH-38. Closes GH-52. Reviewed-by: Christian Murphy <[email protected]>
1 parent 35d12e3 commit b8f9d15

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

readme.md

+55
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,61 @@ Yields:
145145
**Importance** and .
146146
```
147147

148+
###### HTML in Markdown
149+
150+
We try our best to map any HTML (hast) to Markdown (mdast) and keep it readable.
151+
Readability is one of Markdown’s greatest features: it’s terser than HTML, such
152+
as allowing `# Alpha` instead of `<h1>Alpha</h1>`.
153+
154+
Another awesome feature of Markdown is that you *can* author HTML inside it.
155+
As we focus on readability we don’t do that, but you can by passing a handler.
156+
157+
Say we for example have this HTML, and want to embed the SVG inside Markdown as
158+
well:
159+
160+
```html
161+
<p>
162+
Some text with
163+
<svg viewBox="0 0 1 1" width="1" height="1"><rect fill="black" x="0" y="0" width="1" height="1" /></svg>
164+
a graphic… Wait is that a dead pixel?
165+
</p>
166+
```
167+
168+
This can be achieved with `example.js` like so:
169+
170+
```js
171+
var unified = require('unified')
172+
var parse = require('rehype-parse')
173+
var stringify = require('remark-stringify')
174+
var vfile = require('to-vfile')
175+
var toHtml = require('hast-util-to-html')
176+
var toMdast = require('hast-util-to-mdast')
177+
178+
var file = vfile.readSync('example.html')
179+
180+
var hast = unified()
181+
.use(parse)
182+
.parse(file)
183+
184+
var mdast = toMdast(hast, {handlers: {svg: svg}})
185+
186+
var doc = unified()
187+
.use(stringify)
188+
.stringify(mdast)
189+
190+
console.log(doc)
191+
192+
function svg(h, node) {
193+
return h.augment(node, {type: 'html', value: toHtml(node, {space: 'svg'})})
194+
}
195+
```
196+
197+
Yields:
198+
199+
```markdown
200+
Some text with <svg viewBox="0 0 1 1" width="1" height="1"><rect fill="black" x="0" y="0" width="1" height="1"></rect></svg> a graphic… Wait is that a dead pixel?
201+
```
202+
148203
## Related
149204

150205
* [`hast-util-to-nlcst`](https://github.com/syntax-tree/hast-util-to-nlcst)

0 commit comments

Comments
 (0)