In a template we want to be able to create a URL to a Robyn endpoint and we don't want to hard code it.
So if we consider the example: https://robyn.tech/documentation/example_app/modeling_routes and imagine that
@app.get("/crimes")
async def get_crimes(request):
renders a template with all the crimes listed. Each crime in the table will need URLs for the details, to edit, to delete. The whole page will need a url to add an additional crime. The end points are all defined in the code:
@app.post("/crimes")
async def add_crime(request):
...
@app.get("/crimes/:crime_id", auth_required=True)
async def get_crime(request):
...
@app.put("/crimes/:crime_id")
async def update_crime(request):
...
@app.delete("/crimes/{crime_id}")
async def delete_crime(request):
Flask uses url_for() to do this eg:
<table>
{% for cime in crimes %}
<tr>
<td><a href={{url_for('get_crime',id=crime.id)}}>{{ crime.description }}</a></td></td>
</tr>
{% endfor %}
</table>
As the example is currently written that URL would resolve to <a href="/crime/42">Crime number 42</a>
The flask url_for has extra capabilities. For example, the need to change the scheme and host is very rare.
The Flask url_for is based on the function name rather than the argument passed to the decorator. If the function name is within a blueprint then the name of the blueprint needs to be in the argument to url_for. In Robyn that means we want the first argument to be the name argument to the SubRouter (in the examples whatever name resolves to eg "frontend") plus the name of the function within that, plus the arguments.
This way if we change the SubRoute prefix or the decorator path the template does not need to be changed.
So these changes will not change the template (as they neither change the name of the module nor the function name)
crimes = SubRouter(__name__, prefix="/sub_router")
@crimes.get("/crimes/:crime_id", auth_required=True)
to
g_crimes = SubRouter(__name__, prefix="/gotham/crimes")
@g_crimes.get("/acrime/:crime_id", auth_required=True)
Note we will still need to change the template if we move the function from global into a SubRouter, change the module name, change the function name, or the function arguments.
Adding this function helps make templates less brittle and more reusable.
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too