universal-shortcodes
v0.9.2
Published
A universal shortcode parser that can work with Wordpress shortcodes, BBCodes and also more customized variants
Downloads
29
Maintainers
Readme
Universal Shortcodes
A universal parser for wordpress shortcodes, BBCode and related markup languages. It is (going to be) highly customizable but for now it should support out of the box everything that wordpress does.
How to use
- Install the library
npm i --save universal-shortcodes
- Import the library:
- In Node.js with
var compileShortcodes = require('universal-shortcodes).compileShortcodes
- In ES6 with
import {compileShortcodes} from 'universal-shortcodes';
- In Node.js with
- Call
compileShortcodes
passing your text and a callback handler for transforming shortcodes. The callback is defined below.
compileShortcodes
callback
The second argument of compileShortcodes
is a callback that takes three arguments:
- the name of the shortcode;
- an object of arguments; named arguments have the key as specified; unnamed arguments are declared as keys 0, 1, 2... from the left;
- contents of the shortcode, in case of self-closed shortcodes it's an empty string.
For example, given shortcode [test "first" "second" value="val1" other="val2"]Inner text[/test]
the following arguments would be passed:
shortcode = 'test'
args = {
0: 'first',
1: 'second',
value: 'val1',
other: 'val2'
}
contents = 'Inner text'
Example usage
import {compileShortcodes} from 'universal-shortcodes';
const text = 'Before anything [strong key="value"]inside strong[/duck] After everything';
const result = compileShortcodes(text, (shortcode, args, contents) => {
const argsArray = Object.keys(args).map(key => {
return `data-${key}="${args[key]}"`;
});
let argsString = argsArray.join(' ');
argsString = argsString ? ` ${argsString}` : '';
if (contents){
return `<${shortcode}${argsString}>${contents}</${shortcode}>`;
} else {
return `<${shortcode}${argsString}/>`;
}
});
console.log(result);
// Before anything <strong data-key="value"/>inside strong<duck/> After everything
Internals
Internal methods are exposed via property _universalShortcodes
- their APIs are unlikely to change should be safe to use if you ever feel a need to do it.
Options
shortcodeOpenCharacter (string 1 character)
, default[
- specifies the character used as the opening of a shortcode.shortcodeCloseCharacter (string 1 character)
, default]
- specifies the character used as the closing of a shortcode.
Currently the options object does not change anything.
Todo:
- Specifying delimiter characters for shortcodes
- Specifying how to handle incorrectly nested shortcodes (crash)