如何在激活html链接时将变量设置为某个东西?
例如,我有一个锚标记转到另一个页面。有没有办法激活一个改变变量的函数?
使用此变量,我想打开一个新页面,如:@ app.route(/ VARIABLE_HERE)
如何在链接上设置变量然后打开页面? 感谢。
更新1:
我基本上有一个名为'topic'的全局变量,它被设置为'maths'。我有一个图像,当点击时会将'topic'的值更改为'english'。
更新2:
我没想到多个用户,我没有进步,我还在学习。基本上我的网站是一个修订工具。我有一个主题列表。当用户点击主题时,将出现一个问题,用户将回答该问题。我正在努力的是,当用户点击主题时,我希望将它们定向到每个主题的同一页面,但我不知道如何让该页面识别用户点击的主题。我想通过在单击主题时设置全局变量,然后在问题页面中读取该变量将以某种方式工作,但就像你说的那样,它对多个用户不起作用。我该怎么做呢?
答案 0 :(得分:2)
您需要在问题中提供更多信息。你是什么意思"设置变量设置为"?将变量设置在哪里?基于什么?
如果要构建带变量的链接,请执行以下操作:
<a href="/{{variable}}">Click here</a>
但这取决于variable
是什么以及它来自何处。在您的问题中提供更多详细信息以获得更好的答案。
修改:我根据您在问题中添加的新信息提供更多信息。很难在这里给你具体的建议,所以我会回应你的每一个要求,试着指出你正确的方向。
让我们考虑一下StackOverflow的工作原理。
以下是基本数据模型:
Question
id
title (text)
body (text)
date (timestamp)
has one User (the author)
has many Answers
has many Tags
Answer
id
body (text)
date (timestamp)
has one User (the author)
Tag
name (text)
User
username (text)
password (hashed and salted text)
...
因此,对于一个非常基本的StackOverflow克隆,我需要这些路由/ URL来执行以下操作:
POST /question
create a new Question for the current User
form input: title, body, tags
GET /question/{id}
pull the Question from the database, along with the author, any Answers,
and any Tags
GET /tags/{name}
pull all the Questions for the given Tag
POST /answer/{question_id}
create a new Answer for the current User under the given question_id
form input: body
(请注意,这只是组织路线的一种方式)
所以在我开始考虑jinja,python,HTML,烧瓶,制作链接,变量等之前,我正在考虑URL的外观以及如何将数据写入和检索数据。数据库中。
我建议您在这一步骤中更加精通(例如,通过阅读一些教程,阅读有关应用程序开发的书籍,参加在线课程/ MOOC,查看一些开源代码,尝试更小的项目),然后再深入研究建立像这样的网站的完全复杂性。
答案 1 :(得分:0)
你需要使用烧瓶提供的路由,就像它要使用的那样。
首先设置主题视图:
# here the first /topic is the url
# and the second /<topic> sets a variable "topic"
# that will be passed to the view function
# so going to url /topic/english, would set the
# topic variable to english
@app.route('/topic/<topic>')
def topic_view(topic):
# then youll prolly get the topic questions from the db? not
# sure how your implementing this
questions = TopicQuestionModel.query.filter_by('topic'=topic).all()
我认为这可能是你所寻找的,只要做@app.route('/<topic>')
就可以做同样的事情,但英语的网址只是/english
而不是/topic/english
。虽然/topic/<topic>
看起来有点令人困惑,但我认为在这种情况下明确地将/ topic添加到url是更好的方法,最终会更易读和理解。