I'm currently building a site with a comprehensive pattern library (along the lines of Lonely Planet's), which Craft seems very well suited to. Each pattern is a partial template and I include it in a page like so:
{% include '_partials/card' with {
title: 'Something',
description: 'A bit of text',
image: 'http://lorempixel.com/400/200/'
} %}
The above, with dummy data, allows me to create an example for the pattern library, but I can then easily reuse the above partial with real data by changing the string values to, eg. entry.title
, entry.description
, etc. This seems to work pretty well for everything apart from for assets: entry.image
is not a string, so there's a type difference with my placeholder image.
So far I've got around this problem with a bit of logic that sets image
to entry.image.first().getUrl()
if entry.image
exists. But it feels like this should really happen inside the partial: firstly it's messy and non-DRY to do this every time / everywhere I include it; secondly, the partial itself should really be able to be responsible for specifying the image transform (if there is one).
So it seems to me there are two possible solutions, but I can't quite figure out how to achieve either. The two options are:
- Allow the partial to accept either a string or an asset as its
image
. - Create a mock asset object in my pattern page that will behave more like an asset if I feed it into the partial, so the partial will work unproblematically when I give it an
entry.image
.
In the former case, I can't figure out a neat way to handle an input that might be a string or an asset field (Twig doesn't seem to have, eg. an is string
test). In the latter case I have no idea how you'd go about it or even whether it's possible.
If anyone has any ideas or experience of how you might achieve the above, I'd be really grateful!