使用车把和 Mandrill-dotnet -library 的 Mandrill 中的每个循环

Each-loop in mandrill using handlebars and Mandrill-dotnet -library

我正在使用 Mandrill 发送电子邮件,并使用 Handlebars 呈现电子邮件中的内容。

如果我像这样添加变量一切正常:

后端:

message.AddRecipientVariable("test@gmail.com", "MYVALUE", "some value");

Html-模板:

<p>{{MYVALUE}}</p>

但是如果我尝试使用 {{#each}} - 已发送电子邮件中的每个部分都是空的。我在这里做错了什么。我是否以错误的方式传递了 objStringArray,或者是否遗漏了其他东西来渲染循环?

后端:

var objList = new List<MyObj> {new MyObj() {Qty = "125"}, new MyObj() { Qty = "16"}};

var jsonSerialiser = new JavaScriptSerializer();
var objStringArray = jsonSerialiser.Serialize(objList.ToArray());

message.AddRecipientVariable("test@gmail.com", "VALUES", objStringArray);

message.merge_language = "handlebars";
_mandrillApi.SendMessage(message, templateName, new List<TemplateContent>());

Html-模板:

<ul>
  {{#each VALUES}}
    <li>{{Qty}}</li>
  {{/each}}
</ul>

Handlebars in mandrill

Mandrill-dotnet

我在 Python 中使用 Djrill,所以我不熟悉您使用的库。

但是您应该确保您的 JSON 没有以

中提到的错误方式嵌套

根据我正在使用的库 (Mandrill-DotNet),方法:AddRecipientVariable() 仅将字符串类型作为内容变量。 madrill-API 在执行 {{#each}} 时需要一个列表。因此,通过稍微更改库源代码,我可以将常规 List<dynamic>() 传递给 AddRecipientVariable-s content-parameter,并且效果很好。

通过更改源代码:

public struct merge_var
{
    #region Fields

    /// <summary>
    ///     The content.
    /// </summary>
    public string content;

    /// <summary>
    ///     The name.
    /// </summary>
    public string name;

    #endregion
}

    public void AddRecipientVariable(string recipient, string name, string content)
    {
        if (this.merge_vars == null)
        {
            this.merge_vars = new List<rcpt_merge_var>();
        }

        rcpt_merge_var entry = this.merge_vars.Where(e => e.rcpt == recipient).FirstOrDefault();
        if (entry == null)
        {
            entry = new rcpt_merge_var { rcpt = recipient };
            this.merge_vars.Add(entry);
        }

        var mv = new merge_var { name = name, content = content };

        entry.vars.Add(mv);
    }

对此(string contentdynamic content):

public struct merge_var
{
    #region Fields

    /// <summary>
    ///     The content.
    /// </summary>
    public dynamic content;

    /// <summary>
    ///     The name.
    /// </summary>
    public string name;

    #endregion
}

    public void AddRecipientVariable(string recipient, string name, dynamic content)
    {
        if (this.merge_vars == null)
        {
            this.merge_vars = new List<rcpt_merge_var>();
        }

        rcpt_merge_var entry = this.merge_vars.Where(e => e.rcpt == recipient).FirstOrDefault();
        if (entry == null)
        {
            entry = new rcpt_merge_var { rcpt = recipient };
            this.merge_vars.Add(entry);
        }

        var mv = new merge_var { name = name, content = content };

        entry.vars.Add(mv);
    }