python - How to perform multiple replacements on string in Jinja2? -


i have pelican website bootstrap3 theme. theme uses font awesome place icons links social media accounts. font awesome class names determined making link text lowercase , substituting spaces dashes.

the problem is, link texts not map font awesome class names. example, envelope icon provided envelope class, want email link text on website.

i can change class names in font awesome stylesheet, won't able use bootstrap cdn , have make such modifications every time update font awesome new version.

i decided modify pelican template instead , make necessary transformations before class name written. far, code looks this:

{% set name_sanitized = name|lower|replace('+','-plus')|replace(' ','-')|replace('stackexchange', 'stack-exchange')|replace('rss-feed', 'rss')|replace('email', 'envelope') %} 

can substitute chain of replace calls using dict? this:

{% set replacements = dict('+' = '-plus', ' ' = '-',                            'stackexchange' = 'stack-exchange', 'rss-feed' = 'rss',                           'email' = 'envelope') %} {% set name_sanitized = name|lower|??? %} 

if not, there other way make part more readable , maintainable in long term?

this looks job custom jinja2 filter.

def dict_replace(text, replacements):     key, val in replacements.iteritems():         text = text.replace(key, val)     return text 

add filter pelican config file:

jinja_filters = {'dict_replace': dict_replace} 

then use filter in template:

{% set name_sanitized = name|lower|dict_replace(replacements) %} 

alternatively, implement in jinja2 directly, it's pretty awkward.

{% set _name_sanitized = {'': name|lower} %} {% 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 necessary because loops have own scope in jinja2 can't update variable set.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -