如何从python代码调用django模板标记?

时间:2023-01-24 11:19:21

I'm writing a very simple custom tag and I want to call django's include tag from my custom tag code.

我正在编写一个非常简单的自定义标记,我想从我的自定义标记代码中调用django的include标记。

e.g. How do I call django.templates.loader_tags do_include (or include) tag from a python code?

如何调用django.templates模板。loader_tags do_include(或包含)来自python代码的标记?

1 个解决方案

#1


1  

I think you would be easier simply rendering the template yourself with the context passed to your template tag instead of using the include tag. For example:

我认为您可以简单地使用传递给模板标签的上下文来呈现模板,而不是使用include标记。例如:

from django.template.loader import render_to_string

@register.simple_tag(takes_context=True)
def my_tag(context):
    html = render_to_string("my_tag_template.html", context)
    ...

That said, if you want to see how the include tags work you can see the code here:

这就是说,如果你想看看include标签是如何工作的你可以在这里看到代码:

https://github.com/django/django/blob/master/django/template/loader_tags.py#L124

https://github.com/django/django/blob/master/django/template/loader_tags.py L124

#1


1  

I think you would be easier simply rendering the template yourself with the context passed to your template tag instead of using the include tag. For example:

我认为您可以简单地使用传递给模板标签的上下文来呈现模板,而不是使用include标记。例如:

from django.template.loader import render_to_string

@register.simple_tag(takes_context=True)
def my_tag(context):
    html = render_to_string("my_tag_template.html", context)
    ...

That said, if you want to see how the include tags work you can see the code here:

这就是说,如果你想看看include标签是如何工作的你可以在这里看到代码:

https://github.com/django/django/blob/master/django/template/loader_tags.py#L124

https://github.com/django/django/blob/master/django/template/loader_tags.py L124