sveltejs/sapper

ability to replace text on template through middleware

Opened this issue · 7 comments

Is your feature request related to a problem? Please describe.
I want to set up (through middleware) the lang and dir attributes for tags in template.html, and Sapper doesn't give me a chance to do so.

Describe the solution you'd like
I already implemented a solution on a PR I'm about to submit.
Basically, what it does is, look for the property replacers in the response object (affectionately known as res) and replace text on the template for every key on that property.
So, if any middleware has put anything on that property, you're good to go.

How important is this feature to you?
I need this to implement better internationalization. And internationalization is VERY important to me.

Im having the same issue, how did you solve it?

Hola Ramiro,
Mirá el título, dice: "May be fixed by #1037" (puede ser arreglado por #1037). 😉

Now in English:
Hello @ramiroaisen, have a look at the title, it reads: "May be fixed by #1037". 😉

How exactly would this work?

arve0 commented

@arxpoetica Before sending document body to the client, sapper could see if any replacers have been defined. For example, adding a replacer for IE user-agents:

express()
	.use(
		function (req, res, next) {
			if (req.get('user-agent').toLowerCase().includes("msie")) {
				res.replacers = {
					script: () => "" // no scripts for Internet Explorer
				};
			}

			next()
		},
		sapper.middleware()
	)
arve0 commented

Another approach could be to give back control to a handler defined in the middleware options:

sapper.middleware({
	done: (req, res, body) => {
		if (req.get('user-agent').toLowerCase().includes("msie")) {
			// do not send scripts
			body = body.replace(/<script.*\/script>/g, '')
		}
		res.end(body)
	}
})

btw I do this with a script I run after build, which uses regexp-replace to swap out tags in template.html. It works well.

I'll have a look at your PR

I didn't realize that this issue/PR existed when I started my work on a PR to address #179, but it accomplishes the same thing in a different way. Though, by the looks of how this has sat for a while, I wonder if this feature is something that the maintainers are interested in. I hope so!