sapper icon indicating copy to clipboard operation
sapper copied to clipboard

ability to replace text on template through middleware

Open vilarfg opened this issue 5 years ago • 7 comments
trafficstars

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.

vilarfg avatar Dec 27 '19 05:12 vilarfg

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

ramiroaisen avatar Feb 13 '20 19:02 ramiroaisen

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

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

vilarfg avatar Feb 14 '20 03:02 vilarfg

How exactly would this work?

arxpoetica avatar Apr 04 '20 19:04 arxpoetica

@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 avatar Apr 11 '20 09:04 arve0

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)
	}
})

arve0 avatar Apr 11 '20 09:04 arve0

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

antony avatar Apr 11 '20 11:04 antony

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!

happycollision avatar Nov 22 '20 06:11 happycollision