【问题标题】:Replacing text with variables用变量替换文本
【发布时间】:2023-03-26 23:41:02
【问题描述】:

我必须向某些客户发送信件,并且我有一封需要使用的标准信件。我想用变量替换消息正文中的一些文本。

这是我的成熟度字母 models.py

class MaturityLetter(models.Model):
default = models.BooleanField(default=False, blank=True)
body = models.TextField(blank=True)
footer = models.TextField(blank=True)

现在 body 的值是这样的:

亲爱的[主要名字],

一个重要的提醒......

您的 [产品] 在 [金融机构] 的 [maturity_date] 到期。

现在我想用我的模板变量替换括号中的所有内容。

到目前为止,这就是我在 views.py 中的内容:

context = {}
if request.POST:
    start_form = MaturityLetterSetupForm(request.POST)
    if start_form.is_valid():
        agent = request.session['agent']
        start_date = start_form.cleaned_data['start_date']
        end_date = start_form.cleaned_data['end_date']
        investments = Investment.objects.all().filter(maturity_date__range=(start_date, end_date), plan__profile__agent=agent).order_by('maturity_date')
        inv_form = MaturityLetterInvestments(investments, request.POST)
        if inv_form.is_valid():
            sel_inv = inv_form.cleaned_data['investments']
            context['sel_inv'] = sel_inv
        maturity_letter = MaturityLetter.objects.get(id=1)
        
        context['mat_letter'] = maturity_letter
        context['inv_form'] = inv_form
        context['agent'] = agent
        context['show_report'] = True

现在,如果我遍历 sel_inv,我可以访问 sel_inv.maturity_date 等,但我不知道如何替换文本。

在我的模板上,到目前为止我只有:

{% if show_letter %}
{{ mat_letter.body }} <br/>
{{ mat_letter.footer }}
{% endif %}

非常感谢。

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

    使用format strings:

    >>> print "today is %(date)s, im %(age)d years old!" % {"date":"my birthday!","age":100}
    today is my birthday!, im 100 years old!
    

    【讨论】:

    • 漂亮我没有意识到你可以 "%(var)s" 来调用字典元素并将它们放在字符串位置。点赞!
    【解决方案2】:

    我认为这是最好的方法。首先,您有一个包含模板的文件,例如:

    Dear {{primary-firstname}},
    AN IMPORTANT REMINDER…
    You have a {{product}} that is maturing on {{maturity_date}} with {{financial institution}}.
    etc ...
    

    因此,您的视图将类似于:

    from django.template.loader import render_to_string
    
    # previous code ...
    template_file = 'where/is/my/template.txt'
    context_data = {'primary-firstname': 'Mr. Johnson',
                    'product': 'banana',
                    'maturity_date': '11-17-2011',
                    'financial institution': 'something else'}
    message = render_to_string(template_file, context_data)
    # here you send the message to the user ...
    

    所以如果你print message 你会得到:

    Dear Mr. Johnson,
    AN IMPORTANT REMINDER…
    You have a banana that is maturing on 11-17-2011 with something else.
    etc ...
    

    【讨论】:

      【解决方案3】:

      一种解决方案是在正文本身上使用 Django 的模板引擎(就像您在呈现页面时所做的那样)。如果文本可由用户等编辑,我确信存在安全隐患。

      更简单的解决方案是简单的字符串替换。例如,鉴于您上面的内容:

      for var, value in sel_inv.items:
          body = body.replace('[%s]' % var, value)
      

      这不是最漂亮的解决方案,但如果你的正文模板是固定的,你需要做这样的事情。

      【讨论】:

      • 如果你走这条路,最好对新代码使用字符串格式化操作this version,因为它的未来证明(注意:Python 2.6+)。
      【解决方案4】:

      您可以使用带有回调的正则表达式替换。与简单的字符串替换或使用 django 的模板引擎相比,它的优势在于您还知道何时使用未定义的变量(因为您可能不想发送这样的信件/电子邮件:)

      import re
      
      body = """
      Dear [primary-firstname],
      
      AN IMPORTANT REMINDER...
      
      You have a [product] that is maturing on [maturity_date] 
      with [financial institution].
      
      etc
      """
      
      def replace_cb(m):
          replacements = {'primary-firstname': 'Gary',
                          'product': 'Awesome-o-tron2k',
                          'maturity_date': '1-1-2012',
                          'financial institution': 'The bank'}
          r = replacements.get(m.groups()[0])
          if not r:
              raise Exception('Unknown variable')
          return r 
      
      new_body = re.sub('\[([a-zA-Z-_ ]+)\]', replace_cb, body)
      

      【讨论】:

      • 我认为这实际上非常复杂。
      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2017-12-20
      • 2022-12-14
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多