Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTre Bey
Courses Plus Student 237 PointsHow to add certain background images to specific post categories?
I am creating a blog that I would like to have certain background images pop up on the 'post-box' depending on which category the post falls under. I'm using a sort of flex-boxy/masonry style grid to layout my posts, and would like my viewers to identify with the content before clicking the post. I tried a 'for post in post.categories' loop and i tried if/elseif loops, but they don't seem to work properly. Each attempt has beein only showing the last background image in the loop for all posts. I know there is a way, but my syntax must be flawed in some way. If anyone has done this or has some insight it would be greatly appreciated! thanks.
2 Answers
karson Adam
32,623 PointsCan yu post example of code?
karson Adam
32,623 Pointshave you trie to use {% if site.categories.lifestyle %}?
Tre Bey
Courses Plus Student 237 Pointsyeah I tried that as well but it didnt work.
Tre Bey
Courses Plus Student 237 PointsTre Bey
Courses Plus Student 237 PointsHey karson, thanks for the reply. So If a post had a certain category, then the background image would match that category. Here's what I tried.
{% for post in site.categories.lifestyle %} .grid-item {background: url(/images/bg-images/lifestyle-bg.svg) no-repeat center center; background-size: cover;} {% endfor %}
{% for post in site.categories.design %} .grid-item {background: url(/images/bg-images/design-bg.svg) no-repeat center center; background-size: cover;} {% endfor %}
That didn't work, and all posts had the same background as the 'design' category do to cascading (i think). Then I tried an if/elsif statement:
{% if post.categories == 'lifestyle' %} .grid-item {background: url(/images/bg-images/lifestyle-bg.svg) no-repeat center center; background-size: cover;} {% elsif post.categories == 'design' %} .grid-item {background: url(/images/bg-images/design-bg.svg) no-repeat center center; background-size: cover;} {% endif %}
That didn't work and just made all posts have the design-bg.svg background as well, regardless of category. I have a few more categories but that's the gist of what i'm trying to do. I know it's possible but I lack the knowledge to actually get it working. If you have any ideas that would be appreciated!