Macro in Liquid Template language
Asked Answered
P

2

7

I'm using Jekyll, which uses the Liquid Template language. I've used Jinja templating in the past, and it has the concept of a macro (just a named function). Does Liquid have something which provides equivalent functionality? If not, is there some Jekyll plugin which will extend Liquid to provide it?

Patter answered 29/5, 2015 at 6:50 Comment(1)
Since it doesn't look like this exists in Liquid, I've opened up the issue on Github.Patter
M
12

You can create includes that accept parameters. It's not quite a macro but it's what I've used successfully on GitHub Pages.

More details and tips for managing includes and using parameters can be found in the Jekyll documentation.

Here's an example:

_includes/email_link.html

<a href="mailto:{{ include.user.email_address }}"
   title="Email {{ include.user.name }}">
    <i class="fa fa-fw fa-envelope"></i>
</a>

about.md

---
layout: page
title: About
---
{% include email_link.html user=site.users.erik %}

_config.yml

users:
    erik:
        name: Erik
        email_address: [email protected]
Masonmasonic answered 29/5, 2015 at 13:40 Comment(1)
There's some gotchas here, as I remember, biggest of which is that includes don't have restricted scope, so variables changed within an include will remain changed after the include.Igal
M
2

This is exactly what Jekyll tags plugins are made for.

Milburr answered 29/5, 2015 at 8:57 Comment(4)
The GitHub Help about supported Jekyll plugins and the GitHub Pages plugin dependencies do not list the Jekyll tags plugin so unfortunately I do not think this solution will work on GitHub Pages.Masonmasonic
So why are you talking about plugins ? Nevertheless, on github pages, @erik-gillespie solution is the one. And thank you for the down vote.Milburr
The OP may not know that the available plugins on GitHub Pages are limited so I thought it pertinent to point out. If the OP is using GitHub Pages as the tags suggest then your answer will not work and if tried, will cause a lot of headaches, hence the downvote.Masonmasonic
Sorry for the confusion. On my current project, I'm using Github to host but doing the compiling with Travis because I have a few extra steps that Pages won't do. However, having a solution that would work on pages would be nice for future projects. Moreover, as I understand the tags solution you're suggesting, I would have to create a new custom tag in Ruby for every snippet of HTML I wanted to reuse. This isn't great.Patter

© 2022 - 2024 — McMap. All rights reserved.