From 1759d8e4d80df3c3dc709c9bace2eb07d5685596 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 6 Oct 2011 10:57:03 -0400 Subject: [PATCH] Added support for anchor link generation. --- CHANGES | 3 +++ flask/helpers.py | 11 ++++++++++- flask/testsuite/helpers.py | 9 +++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index a1b9fedc..76ac8a22 100644 --- a/CHANGES +++ b/CHANGES @@ -8,6 +8,9 @@ Version 0.9 Relase date to be decided, codename to be chosen. +- The :func:`flask.url_for` function now can generate anchors to the + generated links. + Version 0.8.1 ------------- diff --git a/flask/helpers.py b/flask/helpers.py index 72c8f170..2471103d 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -18,6 +18,7 @@ import mimetypes from time import time from zlib import adler32 from threading import RLock +from werkzeug.urls import url_quote # try to load the best simplejson implementation available. If JSON # is not installed, we add a failing class. @@ -184,9 +185,13 @@ def url_for(endpoint, **values): For more information, head over to the :ref:`Quickstart `. + .. versionadded:: 0.9 + The `_anchor` parameter was added. + :param endpoint: the endpoint of the URL (name of the function) :param values: the variable arguments of the URL rule :param _external: if set to `True`, an absolute URL is generated. + :param _anchor: if provided this is added as anchor to the URL. """ ctx = _request_ctx_stack.top blueprint_name = request.blueprint @@ -204,8 +209,12 @@ def url_for(endpoint, **values): elif endpoint.startswith('.'): endpoint = endpoint[1:] external = values.pop('_external', False) + anchor = values.pop('_anchor', None) ctx.app.inject_url_defaults(endpoint, values) - return ctx.url_adapter.build(endpoint, values, force_external=external) + rv = ctx.url_adapter.build(endpoint, values, force_external=external) + if anchor is not None: + rv += '#' + url_quote(anchor) + return rv def get_template_attribute(template_name, attribute): diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index 052d36e1..80729821 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -288,6 +288,15 @@ class LoggingTestCase(FlaskTestCase): self.assert_equal(rv.status_code, 500) self.assert_equal(rv.data, 'Hello Server Error') + def test_url_for_with_anchor(self): + app = flask.Flask(__name__) + @app.route('/') + def index(): + return '42' + with app.test_request_context(): + self.assert_equal(flask.url_for('index', _anchor='x y'), + '/#x%20y') + def suite(): suite = unittest.TestSuite()