This documentation refers to the version 1.x of the plugin. Take a look here for latest releases.
npm i -D vite-plugin-twig
/* vite.config.js */
import { defineConfig } from 'vite'
import twig from 'vite-plugin-twig'
export default defineConfig({
// ...
plugins: [
twig()
]
})
The plugin can be configured both via the twig.config.js file from the project root or by passing a configuration object directly as argument to the function above (in this last case, the configuration file will be ignored).
Here below the list of the supported options.
type { [key: string]: (...args: any[]) => any }
default {}
A collection of custom filters to extend Twig. Look at twig.js documentation to learn more.
type { [key: string]: (...args: any[]) => any }
default {}
A collection of custom functions to extend Twig. Look at twig.js documentation to learn more.
type { [key: string]: any }
default {}
The global variables to be injected in each template.
type { [key: string]: any }
default {}
The Twig settings. Please refer to twig.js documentation to learn more.
The html files located by default in the Vite project root are not intented to be replaced directly by the twig ones as the normal page files resolution/linking on the Vite's dev server is wanted to be preserved along with the build logic. However, those files are supposed to contain a json definition instead of the traditional markup, which should be moved on the twig side.
More in details, a html file should look like this:
<!-- index.html -->
<script type="application/json">
{
"template": "path/to/template.twig",
"data": {
"title": "Homepage"
}
}
</script>
where template
is the path of the twig template to be rendered (relative to the cwd), and data
is the local context for that page (eventually merged with the globals provided via plugin options).
ℹ️ The script tag is not mandatory, since a plain text representation of the json will be correctly parsed too. However, it is recommended for readability and syntax highlighting purposes.