I'm using Node.js, Express 4, and the Handlebars templating processor. Some of the page views that I'm rendering with Handlebars have several kBytes of static inline SVG code. Is there a simple clean way to put the SVG code into a separate file to be included in the Handlebars layout template? Ideally this include file would have a .svg extension, but .hbs would be acceptable.
Asked
Active
Viewed 7,207 times
3 Answers
4
yesterday I was solving the the same problem. And I finished with loading svg file into string and then pass it to the handlebars template.
var svgTemplate = fs.readFileSync('./public/app/build/images/spriteAll.svg', 'utf8');
var express = require('express'),
router = express.Router();
router.get('/', function (req, res) {
res.render('main', {
svgTemplate: svgTemplate
});
});
//where main.hbs contains: ...
<body class="ng-cloak">
<div class="inline-svg">
{{{svgTemplate}}}
</div>
....
</body>

Romick
- 163
- 1
- 1
- 11
-
Romick I like your solution better than using Handlebars partials to include a file. Your solution allows .svg extension on the include file. – natesrc Feb 16 '17 at 07:08
-
But if it was a handlebars partial it would be included in the handlebars caching. This solution will have the request wait for an svg file to be read from the drive every time `/` is requested. I would at least read all my SVG file into memory when node starts. – gwest7 Mar 28 '19 at 07:00
-
But my solution is already doing what you just said. I have gulp process that collect all svg files process them and return one svg file. Then when server starts I read those file into a string and that string is in memory all the time while node server up – Romick Mar 28 '19 at 11:28
0
You can make a static assets folder (e.g. /public
) in your project, and include it with Express: app.use(express.static('public'));
Put your .svg file in there.
Then in your handlebars file simply add the SVG as you would in a normal HTML project, like <img src="your.svg">

Shruggie
- 869
- 6
- 20
-
1Ben using an img tag to link the SVG file limits the ability of CSS to style the SVG image. Using inline SVG in the HTML loads the SVG into the DOM, making it accessible for re-styling with CSS. I'm looking for a method to put the inline SVG into a Handlebars include file to avoid bloated markup. – natesrc Feb 11 '17 at 11:41
0
You could try out handlebars-partial-file to include a file's contents as a Handlebars partial.

Michio
- 297
- 2
- 7