Blog

Localizing content

Every Simpla element has a Content ID (sid / gid). Whenever this ID changes, the element re-fetches its data, and in the case of <simpla-block>, forces all children to re-fetch their data as well.

By using Javascript to dynamically change the Content ID of a section based on location, we can localize whole sections of content instantly.

Tinker with a CodePen here, where you can see this in action.

Setting up your page

We are going to localize our page by wrapping it in a simpla-block with a locale string (eg: en) as the SID. This will create a new namespace for our content based on locale.

Start by wrapping your content in a simpla-block and assigning a default sid. This will be your default view, so users will still see content even if your localization script fails.

In our example, we've set our default view to English by assigning our block an sid of en.

<simpla-block id="localize" sid="en">

  <simpla-block sid="welcome">  
    <simpla-text sid="blurb"></simpla-text>
    <simpla-text sid="btn" inline></simpla-text>
  </simpla-block>

</simpla-block>  

All of the block's children - in this case, sid="welcome" and its children - hold content that belongs to the block's namespace, en.

In other words, Simpla fetches:

  • en.welcome.blurb
  • en.welcome.btn

Creating localized content

Create the content for all the locales you want to support by manually changing the sid of your section and saving content for each language.

In our example, we’ve implemented a button that will change our sid for us, allowing us to toggle between English and Spanish.

Serving localized content

Now we just have to change the section's sid based on the user's location.

We get the user's preferred language from the browser navigator object.

var locale = navigator.language;  

Then if the user's language is Spanish we localize our content by setting the wrapper's SID to the locale we fetched ('es').

var locale = navigator.language,  
    page = document.querySelector('#localize');

if (locale === 'es') {  
  page.sid =  locale;
}

This fetches the Spanish content we saved for that namespace earlier. If the locale isn't Spanish, we serve the default en content.

That's it!

By taking advantage of Simpla's on-the-fly data structuring we've managed to localize our content with just a few lines of Javascript.

Content IDs are integral in both understanding and maximizing Simpla's utility. By structuring data with namespaces you can serve content that is specific to your users.

Have another great use case for Simpla? Share with us on our slack channel.