最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Jinja的模版中如何跳转到带参数的路径中

Jinja crifan 2565浏览 0评论

已有:

<a href=”{{ url_for(‘show_event’, eventId = todayEvent.id, curUserOpenid = curUser.openid) }}” class=”item-link item-content”>

然后希望是对于url_for调用的路径show_event,加上参数,变成

show_event/eventId

jinja url_for path with para

python – Variable in Flask static files routing [url_for(‘static’, filename=”)] – Stack Overflow

python – Create dynamic URLs in Flask with url_for() – Stack Overflow

好像直接就是:

<code>{{ url_for(find_question,question_id=1) }}
</code>

就可以传入到:

@app.route(‘/questions/<int:question_id>’):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return (‘you asked for question{0}’.format(question_id))

就可以得到:

question_id

去试试,果然可以的。

即:

/Users/crifan/dev/dev_root/daryun/SIPEvents/sourcecode/flask/sipevents/templates/index.html

<a href=”{{ url_for(‘show_event’, event_id = todayEvent.id, curUserOpenid = curUser.openid) }}” class=”item-link item-content”>

/Users/crifan/dev/dev_root/daryun/SIPEvents/sourcecode/flask/sipevents/views.py

@app.route(‘/show_event/<int:event_id>’, methods=[‘GET’])
def show_event(event_id):
    requestMethod = request.method
    requestArgs = request.args
    app.logger.debug(‘requestMethod=%s, requestArgs=%s’, requestMethod, requestArgs)
    app.logger.debug(‘type(event_id)=%s, event_id=%s’, type(event_id), event_id)
    # eventId = request.args.get(“eventId”, “”)
    eventId = event_id
    app.logger.debug(‘type(eventId)=%s, eventId=%s’, type(eventId), eventId)

就可以得到对应参数的int值了:

DEBUG in views [/usr/share/nginx/html/SIPEvents/sipevents/views.py:396]:
type(event_id)=<type ‘int’>, event_id=1

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/usr/share/nginx/html/SIPEvents/sipevents/views.py:400]:
type(eventId)=<type ‘int’>, eventId=1

[总结]

此处,想要在url_for中,传递路径中带参数的路由,则可以用:

url_for(‘show_event’, event_id = todayEvent.id

和:

@app.route(‘/show_event/<int:event_id>’, methods=[‘GET’])
def show_event(event_id):
    app.logger.debug(‘type(event_id)=%s, event_id=%s’, type(event_id), event_id)

 记得对应的类型的参数了。

转载请注明:在路上 » [已解决]Jinja的模版中如何跳转到带参数的路径中

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.162 seconds, using 22.13MB memory