I use django template index.html
to render the frontpage. It includes another template to create a link icon. This template url_icon.html
includes another template icon.html
. When passing the arguments down the way, I face with an error. How to fix it?
index.html
.
.
.
{% include "url_icon.html" with name="return" url="/" %}
.
.
.
url_icon.html
<a href="{{url}}">{% include "icon.html" with icon={{ name }} %}</a>
icon.html
<img src="/static/images/{{ name }}.png" />
Causing an error:
Could not parse the remainder: '{{' from '{{'
CodePudding user response:
it looks like there are a few things you can do to improve/fix this. Addressing #1 and #2 should fix your issue. I've also added suggestions for best practices that would probably require refactoring (#3, #4).
- It looks like you need to remove the curly-braces from
name
inside the{% include %}
tag. Context variables can be used inside tags without extra syntax.
url_icon.html:
{% include "icon.html" with icon=name %}
- icon.html will have access to
name
since you're not using theonly
keyword when updating its context, so your code might appear to work at first ({% include %} documentation). However, it looks like your intention is to refer to it asicon
.
- Use the variable
icon
in instead ofname
icon.html:
<img src="/static/images/{{ icon }}.png" />
- Optional suggestion: Use Django's staticfiles system
Try using the {% static %}
tag for your icon. This will help make deployment easier, especially if you use a separate CDN from your webserver. There's lots of literature on how to set up staticfiles for Django projects in production, it's a large topic, but you'll be able to approach it more easily if you use the {% static %}
tag from the beginning.
- Optional suggestion: Django's URL routing system
Your route in index.html
is hard-coded to be "/"
. Django has a powerful URL referencing system to leverage. If you've defined the root URL /
using Django too, you can refer to it by name. Docs: {% url %}, and for the back-end, reverse().