Reputation: 51
I hope this makes sense... I am building a crypto asset list page (easy); however, in the {% for %} loop I would like to include a variable inside a variable. Showing the code will make more sense:
Tempalte.html
{% for crypto_asset in objects__list_cryptoAssets %}
<tr role="row" class="body-row">
<td role="cell">{{ api_external_prices.bitcoin.usd }}</td>
</tr>
{% endfor %}
So the {% for %} loop grabs all the crypto assets and then I can use Django template {{ asset_class.slug }} to grab all slugs... nothing exceptional here. This variable {{ api_external_prices.bitcoin.usd }} grabs external USD prices for Bitcoin, {{ api_external_prices.bitcoin.eur }} prices in EUR, and so forth... nothing exceptional here either.
Here is where the question comes :: the idea would be to have something like {{ api_external_prices.{{ asset_class.slug }}.usd }}... so each crypto would have its own price FX fetched correctly. Is it possible to have a variable inside a variable?
Upvotes: 3
Views: 209
Reputation: 32884
They are several ways you can implement this:
You can create a template filter api_external_prices
that takes asset_class
and the crypto type as parameters and returns the value.
The syntax would be something link this, where api_external_prices
is the name of the template filter:
{{ asset_class|api_external_prices:"usd" }}
See here for more info about this feature: https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#writing-custom-template-filters
Another approach would be to have api_external_prices
as method on your asset_class
object, which returns an object that has a usd
property. api_external_prices
here can just be a wrapper that calls a central module/function, but this would make it much easier to use it in templates.
{{ asset_class.api_external_prices.usd }}
The first approach is similar to what you are asking, but personally I would prefer to use the 2nd approach, because it saves you from introducing as template filter.
Upvotes: 1