amannn
amannn

Reputation: 53

PHP string templating

does anybody of you know about a good way of building string templates, that can be filled with corresponding data afterwords? It's for a communication system.

So a desired output could look like:

Hello Batman, how are you doing? Your friends Superman, Catwoman and Spiderman are already using our service. Would you like to give our service a try?

The actual data should be pulled from the database and so there needs to be a general way of processing something like this:

Hello {Username}, how are you doing? {If:HasFriendsWhoUseTheService}Your friends {ListFriends} are already using our service.{EndIf} Would you like to give our service a try?

So that means in case the user doesn't have friends who are using the system, the middle sentence shouldn't be printed.

I've just built a small system that is capable of replacing fields like {username} or {ListFriends} appropriately, but then I recognized, that there also should be some if statements.

Does anybody know a library or something similar that supports such stuff? Maybe there is also more to consider, for a maximum of flexibility.

Upvotes: 0

Views: 234

Answers (3)

amannn
amannn

Reputation: 53

Thanks for the helpful answers!

I had a talk with the involved managers and had the requirements refined, to make it easier. So i ended up providing only simple fields like {Username} or {Address}, since there is no easy way to create a universal system.

Thanks anyway for your help!

Upvotes: 0

Hieu Le
Hieu Le

Reputation: 8415

Build a custom parser. You can view a BBCode parser in this link as an example http://forrst.com/posts/Simple_PHP_BBCode_Parser-N0z As I understood, you string template will works with tags like {Username}, {if:Condition}Content{/endif}, ... which is the same as what BBCode do.

Upvotes: 0

Jon
Jon

Reputation: 437424

If the templates are only going to be edited by trusted people, then you should simply use PHP itself:

Hello <?php echo $Username;?>, how are you doing?
<?php if ($ListFriends) : ?>
Your friends <?php echo $ListFriends;?> are already using our service.
<?php endif; ?>
Would you like to give our service a try?

If it's not acceptable to allow the template authors full programming capabilities then you can look into a template engine like Smarty (crash course here).

Upvotes: 1

Related Questions