Velo, NPM Package

Easily add dynamic data to your formatted text

Joris Borgers

Written By

Joris Borgers

Amsterdam, Netherlands

Joris likes to travel all over the world. He loves the latest developments in coding. He finds it exciting to find the best solution for clients. Realising the best solution in cooperation with the World of Wix specialists is Joris at his best.

Are you not yet using the Lodash template function to add dynamic data to your text 🤯??! Let me show you what you are missing!

Easily add values to formatted text

Linking a text field to a dataset is a great way to easily set up a page with customizable content. But oftentimes it limits your creative freedom if you want different typography for certain parts of the text. You could fiddle with aligning multiple text fields just right and accounting for all string lengths, but luckily there is a better way! Using the .template function from the Loadash NPM package allows you to easily add variables in text elements. By using the HTML property of the text we can keep the exact formatting we added in the editor and add multiple variables (varying in length) without elements moving around.

It also works great with multilingual websites since you can change the text in between the variables right in the editor.

 



 

How to add the logic

First we have to import the lodash NPM package at the top of the page code.

import _ from 'lodash/string';

We will only be using the string methods, so import from loadash/string to decrease the package size and loading time.

I would also recommend setting the interpolate setting to the below value in the page OnReady event. This will make it so all text in between {{}} will be a variable so it matches the standard Wix uses in the triggered emails.

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;

Then we need to initiate the template by setting a variable to the _.template function and providing the HTML value.


let priceTextFull = _.template($w('#text291').html);

Now we can set the text value to the by adding the variables to the function. Here you can set any values you added to your text.


$w('#text291').html = priceTextFull({
  p: 'price text here',
  d: 'discount text here'
  })

Now the variables will be added in the text and the formatting will remain the same 🥳.


Together we make your website smarter and faster