django blocktrans和标签 - DRY方法

时间:2015-02-03 00:56:58

标签: django django-templates

如何使用以下代码段创建DRY方法?

这可能是一个简单的问题,但它让我感到难过。

过去两天我试过了,但是在将django与标签合并时,我无法弄清楚如何只使用一个blocktrans。

这是我的模板标记代码:

{% if user.userprofile.subscription_category == subscription_type_free %}
    {% with temp_max_language_versions=max_language_versions_free_subscription %}
        {% blocktrans %}You have the ability to create <strong>{{ temp_max_language_versions }}</strong> different {{ resume_details_tran }} with your <a href="{{ user_account_details }}">subscription</a>.{% endblocktrans %}
    {% endwith %}

{% elif user.userprofile.subscription_category == subscription_type_03 %}
    {% with temp_max_language_versions=max_language_versions_level03_subscription %}
    {% blocktrans %}You have the ability to create <strong>{{ temp_max_language_versions }}</strong> different {{ resume_details_tran }} with your <a href="{{ user_account_details }}">subscription</a>.{% endblocktrans %}
    {% endwith %}

{% elif user.userprofile.subscription_category == subscription_type_06 %}
    {% with temp_max_language_versions=max_language_versions_level06_subscription %}
        {% blocktrans %}You have the ability to create <strong>{{ temp_max_language_versions }}</strong> different {{ resume_details_tran }} with your <a href="{{ user_account_details }}">subscription</a>.{% endblocktrans %}
    {% endwith %}

{% elif user.userprofile.subscription_category == subscription_type_12 %}
   {% with temp_max_language_versions=max_language_versions_level12_subscription %}
       {% blocktrans %}You have the ability to create <strong>{{ temp_max_language_versions }}</strong> different {{ resume_details_tran }} with your <a href="{{ user_account_details }}">subscription</a>.{% endblocktrans %}
   {% endwith %}

{% endif %}

1 个答案:

答案 0 :(得分:2)

您的HTML始终与不同的temp_max_language_versions变量相同。解决这个问题的三种方法:

1 - 使用包含:

{% if user.userprofile.subscription_category == subscription_type_free %}
    {% include 'path_to_include.html' with  temp_max_language_versions=max_language_versions_free_subscription %}
{% elif user.userprofile.subscription_category == subscription_type_03 %}
....

2 - 或者您可以将其添加到类别本身;一些伪代码:

class SubscriptionCategory(...):

    @property
    def temp_max_language_versions(self):
         if self.type == 'something':
              return 'something_else'

3 - 如果它特定于视图,您也可以通过视图将其添加到类别中。