Search code examples
expressionengine

Populating a preload_replace variable based on an embed conditional


I like to have both thumbnail and og:image meta tags populated for the pages I build (for use by Facebook, Google and other services), and am trying to streamline my approach.

I want a generic, site-wide image to be specified when displaying a page with no specific image assets, while being able to specify a specific image when warranted (passed via an embed variable).

Here is my approach:

{embed="_global/_header" thumbnail="http://mysite.com/images/articles/some-image.jpg"}

Then in _header:

{if embed:thumbnail}{preload_replace:thumbnail="{embed:thumbnail}"}{/if}
{preload_replace:thumbnail="{site_url}/assets/img/thumbnail.jpg"}

...

<meta name="og:image" content="{thumbnail}" />
<meta name="thumbnail" content="{thumbnail}" />

This works great when I'm passing a thumbnail URL via the embed (as the first value set for a preload_replace variable is used and subsequent ones are ignored), but when I do not pass a value, {thumbnail} ends up empty (rather than using my assigned {site_url}/assets/img/thumbnail.jpg value).

Can anyone see an error in my approach here? Why would {thumbnail} be parsed within my conditional (ending up empty) when I haven't passed that embed variable?


Solution

  • The following works when I try it in EE2.5.3:

    {if embed:thumbnail == ''}{preload_replace:thumb="/assets/img/thumbnail.jpg"}{/if}
    {if embed:thumbnail != ''}{preload_replace:thumb="{embed:thumbnail}"}{/if}
    

    If I reverse the order, it does not work and I get the behaviour you reported - fine if there is an embed parameter and empty otherwise.

    As to exactly why this order works, I don't know - perhaps parse order related like so many EE quirks. Hopefully someone else can explain why it works and we can all learn :)