Update string that was loaded from a txt file

Hi everyone,

I run into a problem, that I’m sure hase an easy fix but I can’t seem to find it.
I’m using the web-client and it shall download an email-template (a text file with .eml as ending) and this e-mail is already prefilled with some values of variables.
This works fine when I have all the text and formating for the .eml in my code window, but as the email will need some nice desinging it will get too many line, so I want to load an external file, exchange the placeholder for the values of the variables and let the user download it as .eml

Loading the template works fine by using var vContent = plugins.file.readTXTFile(vPath), but how do I update the placeholders in vContent for the values of my variables?

Thanks for any help.

Cheers,
Alexander

Hi Alexander,

if im understanding you correctly youre trying to replace some placeholder-strings in your imported vContent?

You can do that with:

utils.stringReplace(vContent,'placeholder','replacement_text')

Hope that helps :)

-Vik

Hi Alexander,

The solution we use for this is a replacePlaceholders method (see below) that sits inside of our utils scope.

/**
 * @param {String} _sText
 * @param {Object} _oValues
 * 
 * @return {String}
 * 
 */
function replacePlaceholders(_sText, _oValues) {
	/** @type {RegExp} */
	var r;
	
	_sText = _sText || '';
	_oValues = _oValues || {};
	
	var _aVars = Object.keys(_oValues);
	
	for (var i = 0; i < _aVars.length; i++) {
		r = new RegExp('\\[' + _aVars[i] + '\\]', 'gi');
		_sText = _sText.replace(r, _oValues[_aVars[i]]);
		
		r = new RegExp('\\{' + _aVars[i] + '\\}', 'gi');
		_sText = _sText.replace(r, _oValues[_aVars[i]]);
	}
	
	return _sText;
}

You will just need to ensure any of the placeholders you want to replace in your email-template file are wrapped in {} or parenthesis.

You can then just invoke the replacePlaceholders method like so:

var vContent = 'Dear {CUSTOMER_NAME}'
var oValues = {
    customer_name: 'John Smith'
}

vContent = replacePlaceholders(vContent, _oValues);

// value of vContent is now 'Dear John Smith'

I hope this helps you solve your issue.

Cheers,

Alex.

Thanks Alex, that solution works perfect!

The above function has been developed to allow placeholders like ‘{CUSTOMER_NAME}’ or [CUSTOMER_NAME]
These stand out nicely in larger texts and the object keys are case-insensitive.

Servoy also supports placeholders out of the box:

var vContent = 'Dear %%CUSTOMER_NAME%%'
utils.stringReplaceTags(vContent, {CUSTOMER_NAME: 'Alexander'})

The Object used in the stringReplaceTags function can also be a record, foundset or form
The docs will provide a little more context on this.

Hope this helps