如何显示基于客户标签的自定义 'Logged in' 欢迎消息? (Shopify/Liquid)

How do I show custom 'Logged in' welcome messages based on customer tags? (Shopify/Liquid)

我有一个从互联网上收集的工作脚本(我不是专家)但我不确定它是否工作正常。但它似乎工作正常。

{% if customer %}
{% assign customer == 'new'}
{% for tag in customer.tags %}
{% if tag contains "wholesale" %}
{%assign customer == 'wholesale' %}
{% endif %}
{% if customer != 'wholesale' %}
  <span>Wholsaler</span>
{% endif %}
{% else %}
  <span>Visitor</span>
{% endif %}

但是现在我遇到了一个我无法解决的问题,我的老板想让我把 liquid script 改成下面这样的东西:

  1. 如果访问者“未”登录,将显示一条消息“您尚未登录”
  2. 如果访问者以“零售”身份登录,将显示一条消息“欢迎零售商”
  3. 如果访问者以“批发商”身份登录,将显示一条消息“欢迎批发商”

我无法让第三个脚本运行,如果有人可以解决我遇到的问题,请指出正确的方向或正确的脚本编写方式?

您的代码试图用非客户对象的内容覆盖 customer 变量。您将需要创建一个新的变量名称以使您的脚本工作。例如,如果有一个登录 customer,则您将该变量设置为等于单词 new。单词 new 没有任何关联的标签,因此 for-loop 中不会发生任何事情。 (此外,您似乎没有使用 endfor 关闭 forloop)

我要提出的另一个建议是使用 contains 关键字而不是 forloop 来检查客户标签。 contains 可用于简单数组(例如标签列表)以检查是否有任何标签与提供的值完全相等,并且比 forloop 更干净、更高效,尤其是当客户有很多标签时标签数。

最终代码可能如下所示:

{% if customer %} 
  {% comment %} Shopper is logged in, but are they special? {% endcomment %}
  {% assign lowercase_tags = customer.tags | join: ',' | downcase | split: ',' %}
  {% if lowercase_tags contains 'wholesale' %}
    {% assign customer_message = 'Welcome, Wholesaler!' %}
  
  {% comment %}OPTIONAL: We can use one or more elsif (Liquid's version of "else if") statements to check for any other special tags, if desired. {% endcomment %}
  {% elsif lowercase_tags contains 'some-other-special-tag' %}
    {% assign customer_message = 'Super Buddy' %}
  
  {% else %} 
    {% comment %} This will be the message for logged-in customers without any special tags {% endcomment %}
    {% assign customer_message = 'Logged in as  ' | append: customer.name %}

  {% endif %}
  {% comment %} Print the appropriate welcome message {% endcomment %}
  <span class="welcome-message">{{ customer_message }}</span>

{% else %}
  {% comment %} Customer is not logged in {% endcomment %}
  <span class="log-in-prompt">You are not logged in</span>
{% endif %}

奖励积分:Shopify 没有将上述客户消息 hard-code 放入模板文件中,而是在 locales 文件夹中为您提供了语言文件。将任何语言文本放入商店的主要语言文件(通常 en.default.json 除非您更改了语言)将允许您在将来使用该主题的“自定义语言”选项编辑该文本。参考:https://shopify.dev/tutorials/develop-theme-localization-use-translation-keys