Add a jinja.render helper

This simplifies some code and will make #1362 possible.
This commit is contained in:
Florian Bruhin 2016-03-25 14:29:30 +01:00
parent e4625a2849
commit 86b12a302e
5 changed files with 30 additions and 44 deletions

View File

@ -70,9 +70,6 @@ def dirbrowser_html(path):
The HTML of the web page. The HTML of the web page.
""" """
title = "Browse directory: {}".format(path) title = "Browse directory: {}".format(path)
template = jinja.env.get_template('dirbrowser.html')
# pylint: disable=no-member
# WORKAROUND for https://bitbucket.org/logilab/pylint/issue/490/
if is_root(path): if is_root(path):
parent = None parent = None
@ -82,18 +79,16 @@ def dirbrowser_html(path):
try: try:
all_files = os.listdir(path) all_files = os.listdir(path)
except OSError as e: except OSError as e:
html = jinja.env.get_template('error.html').render( html = jinja.render('error.html',
title="Error while reading directory", title="Error while reading directory",
url='file://{}'.format(path), url='file://{}'.format(path), error=str(e),
error=str(e), icon='')
icon='')
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')
files = get_file_list(path, all_files, os.path.isfile) files = get_file_list(path, all_files, os.path.isfile)
directories = get_file_list(path, all_files, os.path.isdir) directories = get_file_list(path, all_files, os.path.isdir)
html = template.render(title=title, url=path, icon='', html = jinja.render('dirbrowser.html', title=title, url=path, icon='',
parent=parent, files=files, parent=parent, files=files, directories=directories)
directories=directories)
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')

View File

@ -16,12 +16,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
#
# pylint complains when using .render() on jinja templates, so we make it shut
# up for this whole module.
# pylint: disable=no-member
# WORKAROUND for https://bitbucket.org/logilab/pylint/issue/490/
"""Handler functions for different qute:... pages. """Handler functions for different qute:... pages.
@ -149,17 +143,16 @@ class JSBridge(QObject):
@add_handler('pyeval') @add_handler('pyeval')
def qute_pyeval(_win_id, _request): def qute_pyeval(_win_id, _request):
"""Handler for qute:pyeval. Return HTML content as bytes.""" """Handler for qute:pyeval. Return HTML content as bytes."""
html = jinja.env.get_template('pre.html').render( html = jinja.render('pre.html', title='pyeval', content=pyeval_output)
title='pyeval', content=pyeval_output)
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')
@add_handler('version') @add_handler('version')
def qute_version(_win_id, _request): def qute_version(_win_id, _request):
"""Handler for qute:version. Return HTML content as bytes.""" """Handler for qute:version. Return HTML content as bytes."""
html = jinja.env.get_template('version.html').render( html = jinja.render('version.html', title='Version info',
title='Version info', version=version.version(), version=version.version(),
copyright=qutebrowser.__copyright__) copyright=qutebrowser.__copyright__)
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')
@ -170,7 +163,7 @@ def qute_plainlog(_win_id, _request):
text = "Log output was disabled." text = "Log output was disabled."
else: else:
text = log.ram_handler.dump_log() text = log.ram_handler.dump_log()
html = jinja.env.get_template('pre.html').render(title='log', content=text) html = jinja.render('pre.html', title='log', content=text)
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')
@ -181,8 +174,7 @@ def qute_log(_win_id, _request):
html_log = None html_log = None
else: else:
html_log = log.ram_handler.dump_log(html=True) html_log = log.ram_handler.dump_log(html=True)
html = jinja.env.get_template('log.html').render( html = jinja.render('log.html', title='log', content=html_log)
title='log', content=html_log)
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')
@ -198,7 +190,8 @@ def qute_help(win_id, request):
try: try:
utils.read_file('html/doc/index.html') utils.read_file('html/doc/index.html')
except OSError: except OSError:
html = jinja.env.get_template('error.html').render( html = jinja.render(
'error.html',
title="Error while loading documentation", title="Error while loading documentation",
url=request.url().toDisplayString(), url=request.url().toDisplayString(),
error="This most likely means the documentation was not generated " error="This most likely means the documentation was not generated "
@ -224,9 +217,8 @@ def qute_help(win_id, request):
def qute_settings(win_id, _request): def qute_settings(win_id, _request):
"""Handler for qute:settings. View/change qute configuration.""" """Handler for qute:settings. View/change qute configuration."""
config_getter = functools.partial(objreg.get('config').get, raw=True) config_getter = functools.partial(objreg.get('config').get, raw=True)
html = jinja.env.get_template('settings.html').render( html = jinja.render('settings.html', win_id=win_id, title='settings',
win_id=win_id, title='settings', config=configdata, config=configdata, confget=config_getter)
confget=config_getter)
return html.encode('UTF-8', errors='xmlcharrefreplace') return html.encode('UTF-8', errors='xmlcharrefreplace')

View File

@ -166,10 +166,8 @@ class BrowserPage(QWebPage):
log.webview.debug("Error domain: {}, error code: {}".format( log.webview.debug("Error domain: {}, error code: {}".format(
info.domain, info.error)) info.domain, info.error))
title = "Error loading page: {}".format(urlstr) title = "Error loading page: {}".format(urlstr)
template = jinja.env.get_template('error.html') html = jinja.render(
# pylint: disable=no-member 'error.html',
# WORKAROUND for https://bitbucket.org/logilab/pylint/issue/490/
html = template.render(
title=title, url=urlstr, error=error_str, icon='') title=title, url=urlstr, error=error_str, icon='')
errpage.content = html.encode('utf-8') errpage.content = html.encode('utf-8')
errpage.encoding = 'utf-8' errpage.encoding = 'utf-8'

View File

@ -71,5 +71,11 @@ def resource_url(path):
image = utils.resource_filename(path) image = utils.resource_filename(path)
return QUrl.fromLocalFile(image).toString(QUrl.FullyEncoded) return QUrl.fromLocalFile(image).toString(QUrl.FullyEncoded)
env = jinja2.Environment(loader=Loader('html'), autoescape=_guess_autoescape)
env.globals['resource_url'] = resource_url def render(template, **kwargs):
"""Render the given template and pass the given arguments to it."""
return _env.get_template(template).render(**kwargs)
_env = jinja2.Environment(loader=Loader('html'), autoescape=_guess_autoescape)
_env.globals['resource_url'] = resource_url

View File

@ -46,16 +46,13 @@ def patch_read_file(monkeypatch):
def test_simple_template(): def test_simple_template():
"""Test with a simple template.""" """Test with a simple template."""
template = jinja.env.get_template('test.html') data = jinja.render('test.html', var='World')
# https://bitbucket.org/logilab/pylint/issue/490/
data = template.render(var='World') # pylint: disable=no-member
assert data == "Hello World" assert data == "Hello World"
def test_resource_url(): def test_resource_url():
"""Test resource_url() which can be used from templates.""" """Test resource_url() which can be used from templates."""
template = jinja.env.get_template('test2.html') data = jinja.render('test2.html')
data = template.render() # pylint: disable=no-member
print(data) print(data)
url = QUrl(data) url = QUrl(data)
assert url.isValid() assert url.isValid()
@ -74,7 +71,7 @@ def test_resource_url():
def test_not_found(): def test_not_found():
"""Test with a template which does not exist.""" """Test with a template which does not exist."""
with pytest.raises(jinja2.TemplateNotFound) as excinfo: with pytest.raises(jinja2.TemplateNotFound) as excinfo:
jinja.env.get_template('does_not_exist.html') jinja.render('does_not_exist.html')
assert str(excinfo.value) == 'does_not_exist.html' assert str(excinfo.value) == 'does_not_exist.html'
@ -86,9 +83,7 @@ def test_utf8():
https://github.com/The-Compiler/qutebrowser/issues/127 https://github.com/The-Compiler/qutebrowser/issues/127
""" """
template = jinja.env.get_template('test.html') data = jinja.render('test.html', var='\u2603')
# https://bitbucket.org/logilab/pylint/issue/490/
data = template.render(var='\u2603') # pylint: disable=no-member
assert data == "Hello \u2603" assert data == "Hello \u2603"