未加星标

A django iconbool filter

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Django's template laguage includes a lot of really useful built-in tags and filters , but sometimes you just need to build your own . There are many reasons why you might want to do this, but I'm lazy, and I like to build filters and tags that let me take shortcuts in the template.

Here's one example of a simple filter that let's me be lazy: an iconbool filter.

Motivation

I really like Font-Awesome , and any time I need to represent a boolean value, I like to use an icon. Here's one such example:

User has Widget?
{% if user.has_widget %}
<i class="fa fa-check"></i> Yes
{% else %}
<i class="fa fa-ban"></i> No
{% endif %}

Now, that's not a lot of code, but if you're doing a lot of this type of markup, it can get tedious really quick (imagine building a grid of this kind of content)!

Wouldn't it be so much nicer to write this, instead? (Yes, it would!)

User has Widget? {{ user.has_widget|iconbool }} Build your custom filter

We can accomplish the above with a simple, custom django filter. Let's call it iconbool . It's going to be a simple function that returns a very simple string of markup based on some input.

from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter("iconbool", is_safe=True)
def iconbool(value):
"""Given a boolean value, this filter outputs a font-awesome icon + the
word "Yes" or "No"
Example Usage:
{{ user.has_widget|iconbool }}
"""
if bool(value):
result = '<i class="fa fa-check"></i> Yes'
else:
result = '<i class="fa fa-ban"></i> No'
return mark_safe(result)

That's it! Put this in your app's templatetags directory (for example: myapp/templatetags/myapp_filters.py ), and remember to load the template library in your templates (e.g. {% load myapp_filters %} ).

And remember, being lazy is good! Don't forget that django template filters can save you lots of work.

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: Django
分页:12
转载请注明
本文标题:A django iconbool filter
本站链接:http://www.codesec.net/view/483602.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(24)