Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced: How to use href in Jinja2

I want to use href in the jinja2 template to send the user to the the specific result based on id to learn more about that particular result. I created a route url : ('view_assessment_result', '/view_assessment_result/{id}') that renders all the details about the specific result based on id.

What I want to do:
When a user clicks on the ID number, they will be sent to the route view_assessment_result/{some_id} that will render the specifics of that page based on the id found in the iteration for a in assessment.... I tried looking into cases, but others seem to be using Flask, which I am NOT using. The template code below is not accomplishing the task at hand.

See code below:

route config:

    #Route convention: resource 'name' 'url dispath'
    config.add_route('view_assessment_result', '/view_assessment_result/{id}')

jinja template

        <tr>
        {% for a in assessment_results %}
                <td><a href="{{ '/view_assessment_result' }}">{{ a.id }}</a></td>
            <td>{{ a.owner }}</td>
            <td>{{a.assessment }}</td>
        </tr>
        {% endfor %}

view configuration that renders specific result sent by href above:

@view_config(route_name='view_assessment_result', request_method='GET', renderer='templates/analyst_view.jinja2')
def view_assessment_result(request):
    with transaction.manager:
        assessment_result_id = int(request.matchdict['id'])
        assessment_result = api.retrieve_assessment_result(assessment_result_id)
        if not assessment_result:
            raise HTTPNotFound()
    #more code
like image 973
thesayhey Avatar asked Oct 13 '15 17:10

thesayhey


2 Answers

You need to add the id into your URL path. One way to add the id (from the Python variable a.id to your URL is to use the % string formatting operator, like so:

<a href="{{ '/view_assessment_result/%s'%a.id }}">{{ a.id }}</a>

Also, if your a.id might include special characters (/, &, etc), you can escape them via the urlencode filter:

<a href="{{ '/view_assessment_result/%s'%a.id|urlencode }}">{{ a.id }}</a>
like image 127
Robᵩ Avatar answered Oct 19 '22 20:10

Robᵩ


You can use request.route_path to generate the URL.

<a href="{{ request.route_path('view_assessment_result', id=a.id) }}">{{ a.id }}</a>

Documentation here: http://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html#pyramid.request.Request.route_path

like image 20
Antoine Leclair Avatar answered Oct 19 '22 18:10

Antoine Leclair