Create independent SVG files using Meteor and iron-router

My goal is to use Meteor and Iron-Router to serve dynamic SVG files with templating capabilities.

To start, I create a new route:

@route 'svg', {
   path: '/svg/:name'
   data: -> { name: this.params.name } # sample data
   layoutTemplate: 'svg'
}

Next, I set up a template:

<template name="svg">
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
      xmlns:dc="http://purl.org/dc/elements/1.1/"
      xmlns:cc="http://creativecommons.org/ns#"
      xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
      xmlns:svg="http://www.w3.org/2000/svg"
      xmlns="http://www.w3.org/2000/svg"
      version="1.1"
      width="500"
      height="500"
      id="svg2">
  <defs
        id="defs4" />
  <metadata
        id="metadata7">
    <rdf:RDF>
      <cc:Work
            rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
              rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
        transform="translate(0,-552.36218)"
        id="layer1">
    <text
     x="55.067966"
     y="838.08844"
     id="text2985"
     xml:space="preserve"
     style="font-size:108.92150116px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;letter-spacing:0px;word-spacing:0px;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;font-family:Source Sans Pro;-inkscape-font-specification:Source Sans Pro"><tspan
       x="55.067966"
       y="838.08844"
       id="tspan2987">{{name}}</tspan></text>
    </g>
  </svg>
</template>

When I navigate to http://localhost:3000/svg/foobar, I encounter the following error (in the browser):

Your app is crashing. Here's the latest log.

=> Errors prevented startup:

While building the application:
client/infrastructureViews/svg.html:2: Expected tag name after `<`
<?xml version="1.0" e...
 ^

=> Your application has errors. Waiting for file change.

Question: How can I instruct Meteor or Iron-Router not to generate the surrounding <html>... structure and recognize the SVG as a spacebars top-level element?

Answer №1

If you're looking to control how IR functions, unfortunately, that's not possible. However, you do have the option to switch to manual mode and create the response yourself.

To start, inform the router that a specific path will be handled on the server side:

this.route('svg', {
  path: '/svg/:name',
  where: 'server'
});

Next, set up a middleware on the server side to handle your response:

WebApp.connectHandlers.stack.splice(0, 0, {
  route: '/svg',
  handle: function(req, res, next) {
    var name = req.url.split('/')[1];    // Extract the parameter
    new Fiber(function () {              // Using Fiber is optional,
                                         // unless interaction with Mongo is required
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.write('Sample output');
      res.end();
    }).run()
  },
});

Note that you won't have access to the templating engine on the server side. To work around this, store your svg file in the /private directory, retrieve it as a text asset, and use underscore template format (e.g., <%= name %> instead of {{name}}) to populate it with data:

var template = Assets.getText('file.svg');
var output = _.template(template, {
  name: 'name',
});

Answer №2

After reading through @HubertOG's response and carefully reviewing the documentation for IronRouter, I have devised a new approach that solely utilizes IronRouter. This method involves incorporating both the where and action options:

Router.map ->
  @route 'svg',
    path: '/svg/:name'
    where: 'server'
    action: ->
      svgTemplate = Assets.getText('svg/drawing.svg')
      svg = _.template(svgTemplate, { name: @params.name })
      @response.writeHead(200, {'Content-Type': 'image/svg+xml'})
      @response.end(svg)

It is important to note that the corresponding SVG file must be stored within a subdirectory of /private, as using ../ does not appear to function in this scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Breaking auto-update functionality when using the 'dd-slick' jQuery plugin to style chained drop-downs

Utilizing the jquery.ddslick.min.js plugin from jQuery for creating customized drop-down menus with image options. Additionally, incorporating the jquery.chained.min.js script to automatically update the content in the second select box based on the select ...

Retrieve the height of a div element in an AngularJS framework, and assign this value to a corresponding attribute of another element

Is it possible to retrieve the height of an element using AngularJS and assign it to another div's attribute? In my Bootstrap website, I have a fixed sidebar that needs to stop before reaching the footer. To achieve this, I currently have to manually ...

In mongoose, documents are able to update autonomously without any explicit request

I have encountered an issue with my verification logic. I am sending email links to users for verification, but they are getting verified even before clicking on the link. Below is the code snippet used for user registration: router.post("/register", asyn ...

Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data. This inquiry tackles the challenge of extracting all value ...

Nextjs compilation error - Unable to locate module: Cannot resolve 'module'

Currently, I am immersed in a nextjs project using wagmi hooks. Recently, Nextjs presented me with an error message indicating that it cannot resolve the 'module' (refer to the error message below). This occurred after resolving the initial error ...

Error in AngularJS: The argument 'fn' is not a function and is undefined

I'm encountering an issue with AngularJS 1.6, and the error message is stating: Error: [ng:areq] Argument 'fn' is not a function, got undefined I suspect the problem lies within my testService, and I'm seeking assistance in identify ...

Cross-Origin Resource Sharing (CORS) Issue: How Angular.JS, Node.JS, and

Encountering problems retrieving data from a http post request to my API. Seeing the following error message: XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

When configuring a domain for Express sessions, it prevents the cookie from being stored

I have encountered an issue with my node.js service application and react frontend. I am utilizing Discord OAuth and express sessions for authentication on my application frontend. Everything functions perfectly when running locally, but upon deploying to ...

Error message encountered: "Node.js Object [object Object] does not support the method"

My application uses Express.js and mongodb, including the mongodb Native driver. I have created a model with two functions for retrieving posts and comments: // Retrieve single Post exports.posts = function(id,callback){ MongoClient.connect(url, fun ...

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

How can one authenticate an express session when sending a POST request?

Is there a way to verify that a user is sending a post request in order to prevent unauthorized posting to a URL? I am currently using express-session for this purpose, but I'm open to exploring alternative methods as well. I attempted to implement t ...

How to troubleshoot missing API data in a Bootstrap 5 modal

I am currently working on a project involving a Pokemon API where I have successfully built the front end using .fetch(). My goal is to create an additional modal that displays some stats. However, I am struggling to get the data from the API to show up in ...

How to extract various arrays of identical objects from a larger array in JavaScript

I am working with an array containing objects of this structure: {id: 543, firstName: 'Ted', lastName: 'Foo', age: 32} My goal is to filter out objects in the array that have the same values for both the firstName and age properties. ...

Directives for Nested Elements in AngularJS

I am currently working on creating two custom elements: <accordion> and <accordion-group-active>. .directive('accordion', function () { return { restrict: 'E', replace: true, transclude: true, ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Unable to execute click events on JavaScript functions after updating innerHTML using PHP and Ajax

To begin, I want to clarify that I am intentionally avoiding the use of jQuery. While it may simplify things, it goes against the purpose of my project. Please note that 'ajaxFunction' serves as a generic example for AJAX requests using GET/POST ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

Using Javascript to iterate through and increase HTML code with values all the way up to 55

I am looking for a way to automatically generate a list of links in an HTML page using JavaScript. I have tried a few scripts, but none have worked for me. This is the current structure of my HTML... <a href="1.html"><img src="images/1.jpg" widt ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

Tips for sharing a variable with an external JavaScript file in ASP.NET

Utilizing the variables from default.aspx.cs within the script of the default.aspx file has been achieved successfully with the following code: public partial class default: System.Web.UI.Page { public string _file = string.Empty; public string _i ...