Search code examples
replacetwigcraftcms

Finding and replacing a dynamically created string in Twig?


There is a product URL that is defined in a field in craft cms.

I need to replace the http with https using Twig

I'm using the find and replace method but am not seeing any changes. Have tried putting the find and replace

 {% set productlUrlUpdate = "http://address" %}
 {% set productUrlUpdate = productUrlUpdate|replace({'http://address' : https://address'}) %}

Before and after the definition of productUrl without seeing anychanges in the <img> when rendered to the browser

{% set productUrl = entry['productUrl'] is defined and entry.productUrl is not empty
? entry.productUrl
%}


 {% set productlUrlUpdate = "http://address" %}
 {% set productUrlUpdate = productUrlUpdate|replace({'http://address' :
'https://address'}) %}


<img src="{{ productlUrl }}" width="1" height="1">

Can someone explain to me where I am going wrong please


Solution

  • The fact you don't see any changes lays in the fact you are doing the replace on the (non-existing) variable productUrlUpdate, instead of the variable you are outputting (productUrl)

    You should just do

    <img src="{{ productlUrl | replace({'http://':'//',}) }}" width="1" height="1">