2

I am trying to call an image in my twig template whose identity is known. Here is my code that does not work

{% set asset = craft.assets.kind('image').folderId('9').filename('fitness-strength-strong-male-1.jpg') %}

{% set thumb = {
    mode: 'crop',
    width: 800,
    height: 600,
    quality: 75,
    position: 'center-center'
} %}

 {% if asset %}
    <img alt="No More Posts" class="img-responsive center-block" src="{{ asset.getUrl(thumb) }}" >
 {% endif %}    

This is not working at all. My folderId is correct (got it from craft_assetfolders table) and filename is copied and pasted. Not sure what I am doing wrong.

1
  • 1
    What happen if you do: {% set asset = craft.assets.filename('fitness-strength-strong-male-1.jpg') %}?
    – Brad Bell
    Oct 21 '16 at 21:44
2

This is more of a suggestion than a real answer (assuming the folderId and filename are correct, what you've got should probably work), but anyway:

I'd strongly advise against hard coding an Asset into a template like this. By creating a Global set with an Assets field, you'll save yourself a lot of (potential) trouble, both short and long term.

Here's how your code could look using a Global set called siteSettings, with an Assets field called noMorePostsImage:

{% set asset = siteSettings.noMorePostsImage.first() %}
{% set thumb = {
    mode: 'crop',
    width: 800,
    height: 600,
    quality: 75,
    position: 'center-center'
} %}
{% if asset %}
    <img alt="No More Posts" class="img-responsive center-block" src="{{ asset.getUrl(thumb) }}" />
{% endif %}

So, the code is (a little bit) simpler than what you currently have, and (more importantly) the chance of something going wrong is much smaller. As a bonus, it'll be much simpler to change the image later on, should the need arise. You'll also avoid future issues if someone e.g. moves or renames the Asset from inside Craft.

If your content editor(s) shouldn't be able to change or remove the image, you can simply exclude the Global set from your content editors' user group permissions (assuming you're not running Craft Personal, of course).

2
  • 1
    That worked perfectly! Thanks for introducing Globals to me. I had not even looked at this feature of craft.
    – hvs
    Oct 24 '16 at 15:46
  • Awesome, very happy it helped you out :) Oct 24 '16 at 16:07

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.