Add lang attribute dynamically to HTML tag

Hey guys,
just tried to find it if there is a way to manipulate Meteor’s HTML tag on the fly? I couldn’t find anything except the code to set it “fixed” on startup. I want to add the lang attribute to my <html> tag to tell Google the language of the page. But this must happen per request, because every page may have another language. Is there a way to do this? I’ve already tried it with Helmet, but this only works on client side and I need it on server side too.

Hi @XTA,

You could try using the addHtmlAttributeHook method of WebApp.

WebApp.addHtmlAttributeHook(() => ({ lang: 'es' }));

Hope this helps

Hey,
thanks for your help. This one only sets the lang attribute on startup. So each request will see the same language.

Actually is a callback that runs per request not on startup. Try that and you will see.

WebApp.addHtmlAttributeHook((req) => {
  if (req.browser.name === 'chrome') {
    return { lang: 'en' };
  }

  return { lang: 'es' };
});

If you want to do it on the client side, you can use the plain old DOM api:

document.documentElement.setAttribute('lang', 'es')

Server side is better for crawlers, so you might need both.

You can use the server side hook to set it based on path:

WebApp.addHtmlAttributeHook((req) => {
  if (req.path.startsWith('en/') {
    return { lang: 'en' };
  }
  return { lang: 'es' };
});
1 Like

Thank you guys, didn’t know that it runs individually per request. So I only have to find a way to make it work with SSR and Helmet, because currently Helmet is setting everything and the language is also set within our React components.

Usually a search engine tries to associate one url with one language. How will they index the content when the lang attribute varies?

Yes right, but when the url changes, we also need to update the lang attribute. Currently we are using the http-equiv meta tag to tell the language, but I don’t think that it has the same impact. When we use the HTML lang attribute, Chrome also asks the user if it should translate the page for him. So I guess this one has a higher prio.

I guess using multiple lang attribute vars for one url isn’t a good idea, because Google will only use 1 value - and you wouldn’t be able to control which language will be shown in the search results.

1 Like