Config Variables and Functions
Maizzle is fully configured in JavaScript, so you can programmatically set config options or process and make data available to your Templates.
Variables
You can define variables and then use them in the config.
Here's a simple example, first let's imagine a data source:
// data.js
module.exports = {
name: 'Maizzle'
}
We can use it in our config like so:
// config.js
const data = require('./data.js')
module.exports = {
name: data.name, // available as page.name in Templates
}
Now you can use {{ page.name }}
in a Template and it would render Maizzle
.
Functions
When using a function, you need to make sure that:
- it returns something
- you invoke it
// config.js
const foo = function() {
return 'manchu'
}
module.exports = {
foo: foo(), // invoke function defined above
bar: function() {
// do stuff and return
return 'baz'
}(), // invoke function
wha: () => imaginaryLib.render('implicit return 👌')
}
You would access those variables under the page
object:
<extends src="src/layouts/base.html">
<block name="template">
<p>{{ page.foo }}</p>
<p>{{ page.bar }}</p>
<p>{{ page.wha }}</p>
</block>
</extends>
Result:
<p>manchu</p>
<p>baz</p>
<p>implicit return 👌</p>
Async
You cannot use async functions like this:
module.exports = {
async foo() {
const {data}= await axios.get('https://example.com/api/foo')
return data.foo
}
}
This is because Maizzle config keys are not run as functions at build time, but instead are run only when used in a Template.
So you run into a race condition where you basically try to use the data before it is made available.
Instead, you can use the beforeCreate
event.