Выполнение getattr () разрабатывает поиск в шаблоне django

Вы можете использовать ниже:

for file in *.vcf 
do 
   name=$(basename -- "$file" .new.vcf) 
   sed -i "s/Sample1/$name/g" "$file" 
done
43
задан jamtoday 10 May 2009 в 05:15
поделиться

4 ответа

Недавно мне также пришлось написать этот код как настраиваемый тег шаблона. Для обработки всех сценариев поиска он сначала выполняет стандартный поиск атрибутов, затем пытается выполнить поиск по словарю, затем пытается выполнить поиск getitem (для работы списков), затем следует стандартному Django. поведение шаблона, когда объект не найден.

(обновлено 26 августа 2009 г., чтобы теперь обрабатывать также поиск по индексу списка)

# app/templatetags/getattribute.py

import re
from django import template
from django.conf import settings

numeric_test = re.compile("^\d+$")
register = template.Library()

def getattribute(value, arg):
    """Gets an attribute of an object dynamically from a string name"""

    if hasattr(value, str(arg)):
        return getattr(value, arg)
    elif hasattr(value, 'has_key') and value.has_key(arg):
        return value[arg]
    elif numeric_test.match(str(arg)) and len(value) > int(arg):
        return value[int(arg)]
    else:
        return settings.TEMPLATE_STRING_IF_INVALID

register.filter('getattribute', getattribute)

Использование шаблона:

{% load getattribute %}
{{ object|getattribute:dynamic_string_var }}


59
ответ дан 26 November 2019 в 23:00
поделиться

I ended up adding a method to the model in question, and that method can be accessed like an attribute in the template.

Still, i think it would be great if a built in tag allowed you to dynamically lookup an attribute, since this is a problem a lot of us constantly have in our templates.

2
ответ дан 26 November 2019 в 23:00
поделиться

I don't think so. But it wouldn't be too hard to write a custom template tag to return an attribute in the context dict. If you're simply trying to return a string, try something like this:

class GetAttrNode(template.Node):
    def __init__(self, attr_name):
        self.attr_name = attr_name

    def render(self, context):
        try:
            return context[self.attr_name]
        except:
            # (better yet, return an exception here)
            return ''

@register.tag
def get_attr(parser, token):
    return GetAttrNode(token)

Note that it's probably just as easy to do this in your view instead of in the template, unless this is a condition that is repeated often in your data.

3
ответ дан 26 November 2019 в 23:00
поделиться

There isn't a built-in tag, but it shouldn't be too difficult to write your own.

0
ответ дан 26 November 2019 в 23:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: