6
votes

I'm using Jekyll and Liquid to generate a static web site on GitHub pages. I have found a template from templated.co (this one, specifically) that I am using for the page's layout.

I have Jekyll delivering the content properly, but I would like to use a different background image on each page (in place of the default that's there now) by using Liquid in the CSS. I have Jekyll/Liquid recognizing the CSS by adding an empty front matter section to style.css, but I cannot get the following line to allow me to tweak the background image as I'd like:

    background: url(../images/{% if page.bgimage %}{{ page.bgimage }}{% else %}{{ site.bgimage }}{% endif %}) no-repeat bottom center;

I can change the background image across all pages by putting bgimage: whatever.jpg in _config.yml, but cannot add a line like bgimage: otherimage.jpg in a page's front matter to have it use otherimage.jpg instead of whatever.jpg as the background image.

Is what I want to do even possible, or do I just have some syntax problems going on?

Thanks in advance for your help.

2

2 Answers

11
votes

Instead of doing inline styles, the best way is to simply add an empty YAML block to the beginning of your existing the CSS file, that way the liquid will be processed.

---
---

/* Your css containing liquid tags */
body {
background: url(../images/{% if page.bgimage %}{{ page.bgimage }}{% else %}{{ site.bgimage }}{% endif %}) no-repeat bottom center;
}

"Front Matter Variables Are Optional: If you want to use Liquid tags and variables but don’t need anything in your front matter, just leave it empty! The set of triple-dashed lines with nothing in between will still get Jekyll to process your file. (This is useful for things like CSS and RSS feeds!)" Source:http://jekyllrb.com/docs/frontmatter/

5
votes

The easy way to do this? Set the image with an inline style direct in your post layout, e.g:

<div class="page-background"
{% if page.bgimage %}style="background-image: url({{ page.bgimage }})"
{% endif %}>

Of course, while not as sound from a semantics standpoint it's not ideal but it does mean you can create background images for posts by only adding to your front-matter and not making css additions as well. It's exactly what I'm doing on my site posts.