Search code examples
htmlshopifyliquidshopify-template

how can i truncate item inside double brackets shopify


I need to truncate the amount of characters that is returned from the title of each product but the file where this change needs to be applied has a set of double brackets wrapped around the specific element that needs truncating (see code)

<div class="boost-pfs-filter-product-bottom">
                <a href="[[itemUrl]]" class="boost-pfs-filter-product-item-title">
                    <h4 class="cl-product-card-name">[[itemTitle]]</h4>
                </a>
                <div class="cl-product-card-price">[[itemPrice]]</div>
                
                <button class="quick-add-btn" [[quickAddAttr]] onclick='window.blubolt.quickadd.open("[[productHandle]]",  {"stockMap": "{}" })'>
                    [[quickAddText]]
                </button>
            </div>

The element that needs truncating is [[itemTitle]] on line 3, but i am not sure how to go about this as the double square brackets is causing issues. Any ideas what is needed to be done here? If any more info is needed feel free to ask

picture1


Solution

  • This should work:

    <div class="boost-pfs-filter-product-bottom">
                <a href="[[itemUrl]]" class="boost-pfs-filter-product-item-title">
                    <h4 class="cl-product-card-name" aria-label="[[itemTitle]]" title="[[itemTitle]]">[[itemTitle | truncate: 20]]</h4>
                </a>
                <div class="cl-product-card-price">[[itemPrice]]</div>
                
                <button class="quick-add-btn" [[quickAddAttr]] onclick='window.blubolt.quickadd.open("[[productHandle]]",  {"stockMap": "{}" })' aria-label="[[quickAddText]] [[itemTitle]]">
                    [[quickAddText]]
                </button>
            </div>
    

    Anything with a pipe | inside a variable will apply a filter, in this case the truncate filter. Filters are functions available in the Liquid language that allow transforming the variable value.

    In my example, please note also

    aria-label is still including the full title because it will render the very important heading and link outline more helpful for people with disabilities. CSS truncation would render this unnecessary.

    title also includes the full title, which gives mouse users a way to expand the title by hovering on it.

    aria-label for the button is helpful for screen reader users who navigate by means of tab. Otherwise, all Quick Add buttons have the same accessible name.