Implementing a similiar Wordpress Shortcode feature in Javascript using Template Strings.
"In a nutshell, a shortcode is a small piece of code, indicated by brackets like
[this]
, that performs a dedicated function on your site."
In Javascript when can implement Shortcodes using Template Strings.
Pretend that we have a template page-template.html
that contains a shortcode gallery
which will be replaced by the code of AwesomeGallery
.
<!-- page-template.html -->
<body>
<div class="my-gallery">
${gallery}
</div>
</body>
This gallery represents the source code of any gallery and may contain the gallery html, style and/or some script.
/* Gallery Constructor - Consider this output as an use example of any gallery library */
function AwesomeGallery () {
return '<div id="awesome-gallery">I\'m a Gallery</div><script>document.querySelector("#awesome-gallery").style.display="block"</script>'
}
The idea is delivering our template with shortcodes full filled with their respective code content.
To handle the replace, we have the LiteralShortcodes
method that receives the template and an object containing the shortcodes and their respective contents.
We combine the function body construtor
and template strings
. It will make all shortcodes keys being arguments of the Function
constructor. After that, we instanciate the function passing all the values.
It will replace the template keys by the values.
/* literal-shortcodes.js */
function LiteralShortcodes (template = '', shortcodes = {}) {
const keys = Object.keys(shortcodes)
const values = Object.values(shortcodes)
const fn = `return \`${template}\``
return (new Function(keys, fn))(...values)
}
module.exports = LiteralShortcodes
An example putting everything together:
const AwesomeGallery = require('awesome-gallery')
const pageTemplate = require('./page-template.html')
const LiteralShortcodes = require('./literal-shortcodes.js')
const shortcodes = {
gallery: AwesomeGallery()
}
const html = LiteralShortcodes(pageTemplate, shortcodes)
this is the html content:
<body><div class="my-gallery"><div id="awesome-gallery">I'm a Gallery</div><script>document.querySelector("#awesome-gallery").style.display="none"</script></div></body>
Find a way to escape nested template strings. eg:
:src="``${baseURL}/my-image.jpg``"
. In this case we need to keep the nested template strings to be used in your vue.js component. A possible solution is escaping $ and `` of template before passing it to fn body.