Complex Variable Names In Django Templates
I am storing coordinate data in a database for a simple board game app and I'm attempting to simplify the template by doing fewer loops in it.
My template is something similar to this currently
{% for y in yrange %}
<tr>
{%for x in xrange %}
<td class='mapTile _{{x}}-{{y}}' data-y='{{y}}' data-x='{{x}}'>
</td>
{%endfor%}
</tr>
{% endfor %}
And assuming im passing a dict called itemLocations
that contains an X and Y coordinate in the key l开发者_StackOverflow中文版ike {'1-1':'Data About Item'}
. I'd like to be able to do lookups directly from that dict inside of the <td>
but I cant figure out if thats possible. Something along the lines of:
{% for y in yrange %}
<tr>
{%for x in xrange %}
<td class='mapTile _{{x}}-{{y}}' data-y='{{y}}' data-x='{{x}}'>
{% if x + '-' + y in itemLocations.keys %}
#Render Item Data In This Space#
{% endif %}
</td>
{%endfor%}
</tr>
{% endfor %}
Sorry if that question meanders, id be glad to provide any further info.
Any time you find yourself thinking "I need to do [this complex thing] in a template", your first answer should be to write a custom tag or filter. In this case, you probably want an inclusion tag - that is, move the if
block with the #Render Item Data In This Space#" markup into its own separate template fragment file, and write a tag along these lines:
@register.inclusion_tag('_render_item_location.html')
def render_item_location(locations, x, y):
key = "%s-%s" % (x, y)
if key in locations:
context = {'location': location[key]}
else:
context = {}
return context
Now your template fragment can just do {% if location %}whatever{% endif %}
, and your original template has {% render_item_location itemLocations x y %}
.
Note I've made a tweak to your code - with a dictionary, x in my_dict
searches the keys anyway, so no need to explicitly call keys()
.
精彩评论