Created
June 14, 2012 22:17
-
-
Save SimonSapin/2933303 to your computer and use it in GitHub Desktop.
A Jinja extension that adds a {% showonmatch 'some css selector' %} tag. The content is removed if (parsed as HTML) nothing in it matches the CSS selector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from jinja2 import nodes | |
from jinja2.ext import Extension | |
from lxml.cssselect import CSSSelector | |
from lxml.html import fromstring | |
class ShowOnMatch(Extension): | |
tags = set(['showonmatch']) | |
def parse(self, parser): | |
lineno = parser.stream.next().lineno | |
selector = parser.parse_expression() | |
body = parser.parse_statements(['name:endshowonmatch'], | |
drop_needle=True) | |
return nodes.CallBlock(self.call_method('_callback', (selector,)), | |
[], [], body).set_lineno(lineno) | |
def _callback(self, selector, caller): | |
"""Helper callback.""" | |
rv = caller() | |
cssselector = CSSSelector(selector) | |
matches = cssselector(fromstring(rv)) | |
if matches: | |
return rv | |
else: | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment