2014-02-12 5 views
1

나는 플라스크를 처음 사용합니다. TemplateAssertionError : 'my_multiplier'동적으로 생성 된 jinja2 템플릿에 대해 필터를 Flask에 등록하려면 어떻게합니까?

무엇 오전라는 이름의 필터 나 오류가

@app.template_filter('my_multiplier') 
def my_multiplier(n): 
    return n*10 

@app.route('/') 
def index(): 
    content = [1,2,3,4,5] 
    tmplate = get_template() 
    html = tmplate.render(content=content) 
    return render_template('index.jinja2',html=html) 


def get_template(): 
    html = Template(u'''\ 
    {% for n in conent %} 
    <tr><td>{{ n | my_multiplier }}</td></tr> 
    {% endfor %}''') 
    return html 

: 내가 AJAX를 통해 요청을하고 테이블에 행을 추가 할 수 있도록 동적으로 내 템플릿을 생성하는 것을 시도하고있다 내가 잘못하고있어? (필터를 제외하면 템플릿이 잘 렌더링됩니다.)

답변

4

필터를 등록하셨습니까? 이 도움이

environment.filters['my_multiplier'] = my_multiplier 

http://jinja.pocoo.org/docs/api/#custom-filters

희망!

+0

내가 잘못하지 않으면 @ app.template_filter ('my_multiplier')가 필터를 등록합니까? –

1

비슷한 문제를 겪고있는 동안 발견했기 때문에 정보를 추가하는 중입니다. http://flask.pocoo.org/docs/0.10/templating/에서

현재 답 : 위의 예를 들어

Registering Filters

If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator.

The two following examples work the same and both reverse an object:

@app.template_filter('reverse') 
    def reverse_filter(s): 
     return s[::-1] 

def reverse_filter(s): 
    return s[::-1] 
app.jinja_env.filters['reverse'] = reverse_filter 

In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2’s builtin filters, for example if you have a Python list in context called mylist:

{% for x in mylist | reverse %} 
{% endfor %} 

그 llamawithabowlcut을 의미 정확하고 같이 영업 이익의 코드가 작동합니다.

설명 된 usecase를 다시 작성하려고했지만 OP가 어디에서 가져 왔는지 확실하지 않습니다. 완전한 코드는 여기에서 더 유용했을 것입니다.

0

Flask app이 정의 된 모듈과 다른 모듈의 데코레이터를 사용하면 아무 이유없이 작동하지 않습니다. 그 다음 단계로 이상한 점을 감안하면 브라우저에서는 behave 테스트에서 작동하지만 브라우저에서는 작동하지 않습니다. 이것은 필터가 아닌 컨텍스트 프로세서에서도 마찬가지입니다.

데코레이터 코드를 보면 이것은 잘못된 것이 아닙니다.

1

편집 : 몇 개월 후이 문제를 다시 생각해 보면 솔루션보다 해킹 일 가능성이 높습니다. 네가 해킹을해도 괜찮 으면 작동하지. 저 버전 2.7.2을 사용하기 위해

은 문서화 된 방법은 없습니다 작업을 을했다 : 아마 이전 버전에서 일

environment.filters['my_multiplier'] = my_multiplier # didn't work 

.

대신 나는 코드를 보면이 방법을 발견 : 사람이 문서 링크가있는 경우

from jinja2 import environment 
environment.DEFAULT_FILTERS['name'] = filter_function 

이 추가 주시기 바랍니다.

+0

이 코드를 삽입 한 파일을 설명해 주시겠습니까? –

+0

나는'jinja2'를 단독으로 사용하기 때문에'jinja2'가 아무 것도 해석하기 전에 실행되는 곳이라면 어디든지 넣을 수 있습니다. 나는 그것을 사용하지 않기 때문에 '플라스크'에 어디에 넣어야할지 모르겠다. 시작시에 실행되는 모든 파일이 작동해야한다고 생각한다. – Mark

관련 문제