Added support for anchor link generation.

This commit is contained in:
Armin Ronacher 2011-10-06 10:57:03 -04:00
parent d04c9a61e3
commit 1759d8e4d8
3 changed files with 22 additions and 1 deletions

View File

@ -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
-------------

View File

@ -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 <url-building>`.
.. 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):

View File

@ -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()