3

I have a site with a lot of asset fields, the assets are translatable. The client has added lots into the English fields but many of the Welsh ones haven't been populated. I want to have things fall back to the English assets in cases where there aren't any in the Welsh.

For the sake of example, lets say we're on an entry page where an image has been uploaded in the English locale but one has not been uploaded in the Welsh locale...

I thought this would work:

{% if entry.assetField | length %}
    {# output whichever the current locale is, if it's populated #}
    <img src="{{ entry.assetField.first().getUrl }}" alt="" />
{% elseif entry.assetField.locale('en_gb') | length %}
    {# fallback to the UK English asset if it exists #}
    <img src="{{ entry.assetField.locale('en_gb').first().getUrl }}" alt="" />
{% endif %}

It doesn't. It will pull English assets if I'm viewing the English version of the page, but it does not fall back when we're on the Welsh version of the page. Furthermore, if I am on the Welsh page and change the code to only reference English, like so:

<img src="{{ entry.assetField.locale('en_gb').first().getUrl }}" alt="" />

Then it doesn't output an image at all. It's like Craft is ignoring the .locale parameter I'm setting.

I'm certain the local values are correct because those are what are in the Locale setting in the CMS.

What am I doing wrong?

3

I think you have to apply locale('en_gb') to the entry and not to the field. So entry.locale('en_gb').assetField.first().url should give you the correct value for the other locale.

  • Oh my word I can't believe I didn't think to try that - that works, thanks. – Matt Wilcox Oct 16 '15 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.