In Google Tag Manager (GTM), the language of the Cookiebot consent banner can be controlled by a GTM variable. This allows you to automatically detect which language your banner should be displayed in.
We assume that you've already implemented the Cookiebot CMP tag in GTM.
While this can be achieved in multiple ways (you may for example create a Custom JavaScript Variable named "Current Language" that returns a two-letter ISO language code based on custom logic), in this example the language is determined by a two-letter language sub-directory (for example: domain.com/xx/), or by the domain extension (for example: domain.nl) if no match is found for a language sub-directory.
If the the domain extension has more than 3 characters, the language will default to English.
Implementation
- Create a new Custom JavaScript Page Variable
- Assign the new variable a name, for example: Current Language
- Add the following code to the text field:
function () {
var h = window.location.hostname.toLowerCase(),
p = window.location.pathname.toLowerCase(),
s = /\/[a-z]{2}\//g.test(p.substring(0, 4))
? p.substring(1, 3)
: h.substring(h.lastIndexOf(".") + 1, h.length);
c = s.length > 2 ? "en" : s;
s == "dk" ? (c = "da")
: s == "no" ? (c = "nb")
: s == "se" ? (c = "sv")
: s == "uk" ? (c = "en")
: c;
return c;
}
Once saved, add the variable to your Cookiebot CMP tag in GTM by setting the "Language" dropdown to "By GTM Variable" and select the {{Current Language}}
variable.
Comments
3 comments
Hi Jacob,
Thank you for your documentation!
What should I write in currentUserPagePathname.indexOf(" ") if I want English to be displayed on my mydomain.com root domain, while German to be displayed on my de,mydomain.com subdomain?
Kind regards,
Ilya
Hi,
you don't have to write custom javascript for that. Simply do the following steps:
That's it...
Hi Stephen,
Thanks for the tip. It's definitely useful, but probably not quite enough by it self.
For example on this page, this property returns "en-US". We would have to trim off the "-US" part to make this work. Using this instead should do the trick: document.documentElement.lang.substring(0,2)
This requires that the lang attribute is set and actually reflects the preferred language though.
Please sign in to leave a comment.