
This processor will eventually replace the `{@example}` inline tags because it provides a cleaner approach that also supports tabbed examples straight out of the box. The idea is that authors will simply add a `path` and (optionally) a `region` attribute to `<code-example>` or `<code-pane>` elements in their docs. This indicates to dgeni that the relevant example needs to be injected into the content of this element. For example, assume that there is an example file `toh-pt1/index.hml` with a region called `title`, which looks like: ``` <h1>Tour of Heroes</h1> ``` Then the document author could get this to appear in the docs as a standalone example: ``` <code-example path="toh-pt1" region="title"></code-example> ``` Or as part of a tabbed group: ``` <code-tabs> <code-pane path="toh-pt1" region="title"></code-pane> </code-tabs> ``` If no `path` attribute is provided then the element is ignored, which enables authors to provide inline code instead: ``` <code-example> Some <html> escaped code </code-example> ``` Also all attributes other than `path` and `region` are ignored and passed through to the final rendered output allowing the author to provide styling hints: ``` <code-example path="toh-pt1" region="title" linenums"15" class="important"> </code-example> ```
34 lines
1.4 KiB
JavaScript
34 lines
1.4 KiB
JavaScript
const { parseAttributes } = require('../utils');
|
|
|
|
/**
|
|
* Search the renderedContent looking for code examples that have a path (and optionally a region) attribute.
|
|
* When they are found replace their content with the appropriate doc-region parsed previously from an example file.
|
|
*/
|
|
module.exports = function renderExamples(getExampleRegion) {
|
|
return {
|
|
$runAfter: ['docs-rendered'],
|
|
$runBefore: ['writing-files'],
|
|
$process: function(docs) {
|
|
docs.forEach(doc => {
|
|
if (doc.renderedContent) {
|
|
// We match either `code-example` or `code-pane` elements that have a path attribute
|
|
doc.renderedContent = doc.renderedContent.replace(/<(code-example|code-pane)([^>]*)>[^<]*<\/\1>/, (original, element, attributes) => {
|
|
const attrMap = parseAttributes(attributes);
|
|
if (attrMap.path) {
|
|
// We found a path attribute so look up the example and rebuild the HTML
|
|
const exampleContent = getExampleRegion(doc, attrMap.path, attrMap.region);
|
|
delete attrMap.path;
|
|
delete attrMap.region;
|
|
attributes = Object.keys(attrMap).map(key => ` ${key}="${attrMap[key].replace(/"/g, '"')}"`).join('');
|
|
return `<${element}${attributes}>\n${exampleContent}\n</${element}>`;
|
|
}
|
|
// No path attribute so just ignore this one
|
|
return original;
|
|
});
|
|
}
|
|
});
|
|
}
|
|
};
|
|
};
|
|
|