Nunjucks检查对象或字符串

时间:2015-04-24 10:16:51

标签: nunjucks

如何检查变量是if块中的对象还是字符串? 似乎无法调用{% if ... %}块内的函数。 其他{{ if() }}语法似乎只适用于内联条件。

我现在解决它来测试当变量是一个对象时应该存在的一些对象属性,但应该有一个更好的解决方案。就像isObjectisString函数

一样

2 个答案:

答案 0 :(得分:5)

您可以使用custom filter

var env = new nunjucks.Environment();

env.addFilter('is_string', function(obj) {
  return typeof obj == 'string';
});

这就是模板的样子:

{% if item|is_string %}yes{% endif %}



var env = new nunjucks.Environment();

env.addFilter('is_string', function(obj) {
  return typeof obj == 'string';
});

var res = env.renderString("{% if item|is_string %}yes{% endif %}", { item: 'test' });

document.body.innerHTML = res;

<script src="https://mozilla.github.io/nunjucks/files/nunjucks.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

自定义过滤器或者您可以......

          private PX.Objects.AR.Customer UpdateContact(ContactRead rexContact, PX.Objects.AR.Customer m, string customerClassID, bool insert = true)
    {

        PX.Objects.CR.Contact defContact = null;

        PX.Objects.AR.CustomerMaintInherit graph = PXGraph.CreateInstance<PX.Objects.AR.CustomerMaintInherit>();

        graph.Clear(PXClearOption.ClearAll);

        //Add Customer and BAccount Records
        graph.BAccount.Current = m;
        m.AcctCD = "V" + rexContact._id;
        m.AcctName = rexContact.system_search_key;
        m.Type = "CU";

        if (insert) {
            m = graph.BAccount.Insert(m);

            defContact = graph.DefContact.Current;
        }  
        else {
            defContact = PXSelect<PX.Objects.CR.Contact, Where<PX.Objects.CR.Contact.contactID, Equal<Required<PX.Objects.CR.Contact.contactID>>>>.Select(this, m.DefContactID);
            graph.DefContact.Current = defContact;
        }

        //Update Default Contact Record
        defContact.ContactType = "AP";
        defContact.FullName = rexContact.system_search_key;

        if (rexContact._related.contact_emails != null)
        {
            if (rexContact._related.contact_emails.Length > 0)
            {                   
                defContact.EMail = (from e in rexContact._related.contact_emails where e.email_primary == true select e.email_address).FirstOrDefault();
            }
        }

        if (rexContact._related.contact_phones != null)
        {
            if (rexContact._related.contact_phones.Length > 0)
            {
                defContact.Phone1 =  (from e in rexContact._related.contact_phones where e.phone_primary == true select e.phone_number).FirstOrDefault();
            } 
        }

        defContact = graph.DefContact.Update(defContact);

        //Change customer class to vendor
        m.CustomerClassID = customerClassID;
        m = (PX.Objects.AR.Customer)graph.BAccount.Update(m);
        graph.Actions.PressSave();

        return m;

    }