Reputation: 4285
I have Pelican website with bootstrap3 theme. That theme uses Font Awesome to place icons by links to social media accounts. Font Awesome class names are determined by making link text lowercase and substituting all spaces with dashes.
The problem is, sometimes my link texts do not map to Font Awesome class names. For example, envelope icon is provided by envelope
class, but I really want Email
as link text on website.
I can change class names in Font Awesome stylesheet, but then I won't be able to use Bootstrap CDN and I will have to make such modifications every time I update Font Awesome to new version.
I decided to modify Pelican template instead and make necessary transformations before class name is written. So far, my code looks like this:
{% set name_sanitized = name|lower|replace('+','-plus')|replace(' ','-')|replace('stackexchange', 'stack-exchange')|replace('rss-feed', 'rss')|replace('email', 'envelope') %}
Can I substitute this chain of replace
calls by using dict
? Something like this:
{% set replacements = dict('+' = '-plus', ' ' = '-',
'stackexchange' = 'stack-exchange', 'rss-feed' = 'rss',
'email' = 'envelope') %}
{% set name_sanitized = name|lower|??? %}
If not, is there any other way to make this part more readable and maintainable in long term?
Upvotes: 5
Views: 6192
Reputation: 13046
This looks like a job for a custom Jinja2 filter.
def dict_replace(text, replacements):
for key, val in replacements.iteritems():
text = text.replace(key, val)
return text
Add the filter to your Pelican config file:
JINJA_FILTERS = {'dict_replace': dict_replace}
Then use the filter in your template:
{% set name_sanitized = name|lower|dict_replace(replacements) %}
Alternatively, you could implement this in Jinja2 directly, but it's pretty awkward.
{% set _name_sanitized = {'': name|lower} %}
{% for key, val in replacements.items() %}
{% if _name_sanitized.update('', _name_sanitized['']|replace(key, val) %}{% endif %}
{% endfor %}
{% set name_sanitized = _name_sanitized[''] %}
The _name_sanitized
variable is necessary because loops have their own scope in Jinja2 so you can't just update the variable with set
.
Upvotes: 4