I would suggest an alternate approach using JavaScript data files. Since you have full access to the file system through Node, you can just manually parse the folder into an array with all the information you need, including the SVG source.
Quick and dirty, might need some adjustments:
// _data/icons.js
const fg = require('fast-glob');
const path = require('path');
const fs = require('fs');
module.exports = function() {
return new Promise(async (resolve, reject) => {
const iconFolder = path.resolve(__dirname, '../path/to/your/icon/folder/');
const svgIcons = await fg('**/*.svg', { cwd: iconFolder };
const iconData = await Promise.all(svgIcons.map(async (name) => {
const nameWithoutExtension = path.parse(name).name;
const source = fs.readFileSync(path.resolve(iconFolder, name), { encoding: 'utf8' });
const sourceWithClass = source.replace('<svg', '<svg class="my-custom-class"');
return { name, source, sourceWithClass, nameWithoutExtension };
}));
resolve(iconData);
});
};
This data file returns an array of objects with the name (or path relative to the icon base folder, if there are subdirectories) and source of each SVG icon in the icon folder. Then you can iterate through that in your template and display the name and sources accordingly.
Note the example above uses fast-glob, though you can of course also manually iterate through the files in the folder using fs.
The same should be possible using collections, since you can put any data strcuture you want in a collection now.
Accessing the data
Eleventy automatically parses data file and makes them available to your templates. So you can access the icon data like this in any template (using Nunjucks syntax as an example):
{% for icon in icons %}
<figure>
{# output the svg source code including the added class. the safe filter is necessary to prevent nunjucks from escaping the SVG code #}
{{ icon.sourceWithClass | safe }}
{# output the file name (excluding the extension) #}
<figcaption>{{ icon.nameWithoutExtension }}</figcaption>
</figure>
{% endfor %}
Note that the variable name used to access the data (here: icons
) depends on the name of the data file. See the documentation for details.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…