Skip to content

Instantly share code, notes, and snippets.

@SimonSapin
Created June 14, 2012 22:17
Show Gist options
  • Save SimonSapin/2933303 to your computer and use it in GitHub Desktop.
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
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