datocms / middleman-dato

A Middleman extension to integrate your website with DatoCMS
https://docs.datocms.com/middleman/overview.html
MIT License
24 stars 7 forks source link

Accessing localised content from another locale as a fallback? #4

Closed hanno-jonlay closed 7 years ago

hanno-jonlay commented 7 years ago

I have a site which is successfully pulling the right localised content with the following tag:

<%= dato.about.title %>

When I'm browsing the en locale, it pulls in the English title. When I'm browsing the fr locale, it pulls the French title.

However, if I'm browsing the French site and no French title is found, nothing is displayed.

I've written a simple helper to make it easier to spot when a value is missing:

def localized(value)
    if value.present?
        return value
    else
        return "TODO"
    end
end

So if I do the following, it will output TODO on the French site, instead of just blank content;

<%= localized(dato.about.title) %>

My question: How could I manually access the default (en) locale in Dato, while browsing the French site? If I can access the English version of the title here, I could easily add a fallback in English if the content was missing. Just like Middleman's :i18n works.

Any pointers?

stefanoverna commented 7 years ago

Right now there's no automatic I18n fallback, but I think you can manually do something like this:

def value_with_fallback(item, field_name, fallback_locale = :en)
  item.send(field_name) or
    I18n.with_locale(fallback_locale) { item.send(field_name) }
end

value_with_fallback(dato.articles.first, :title)
hanno-jonlay commented 7 years ago

Awesome, thanks @stefanoverna that'll do me for now 😄