开发者

Can I use alias field names in django templates?

I'm new to django and python...

I have a model which includes 10 generic fields attri开发者_如何学编程b_00 through attrib_09.

I pass these fields as a context to a django template string.

I would like to use more meaningful names in the template.

The template strings are fetched from another model and I have in mind adding a field containing a comma delimited list of associated alias names. The idea being the first alias in list maps to attrib_00, the second to attrib_01...

I'm thinking I need to modify the context before rendering so the generic keys are replaced with the alias's.

Am I on the right track here?

Is there a better way?

Thanks, Ed

P.S.

(add comment button not working for me?)

I don't really have any code yet. Maybe I should explain what I'm trying to acheive...

I have an existing application written in delphi that helps me maintain a large number of ebay listings and I would like to emulate this as a django/python web application.

Each product/listing belongs to a category and each category has a set of attributes. So for example trousers might have color, waist_size and leg_length. The number and type of attributes for each category varies but never exceeds 10.

I can see how for example attrib_00 could be used for size in one category and say metal in another but then would be stuck with using the generic field names in the template.

Just for info:- I guess I would be doing any looping in the view with multiple calls to the rendering process before returning a response?


I would say to make your aliases in the context before passing from the view to the template. Something along the lines of:

c = Context({'foo': attrib_01, 'bar': attrib_02, ...})

You can plug this into a new function so that you don't break DRY and you're good to go.

Update:
As far as actually mapping this within the template, not so much. The template is, after all, just a template. The only thing coming close to working like you're thinking is a {% with %} block:

{% with attrib_01 as foo %}
   <div class="foo">{{ foo }}</div>
{% endwith %}

It would likely work, but I fear it could get rather ugly.


How about using translations?

attrib_00 = models.TextField(_('attrib_00'), blank=True, null=True)

And then have different translations for attrib_00 as required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜