开发者

How to store text with variables into database?

开发者 https://www.devze.com 2023-04-05 19:34 出处:网络
I want to storetext/string in a text field in a database. This string has the variable $name in it. When I pull it out of the database, I want tha开发者_如何学Pythont variable to be substituted with t

I want to store text/string in a text field in a database.

This string has the variable $name in it.

When I pull it out of the database, I want tha开发者_如何学Pythont variable to be substituted with the value I define before I print the string.

   # Variable I want to substitute #
1. $name='John';

   # needs to be read from database #
2. $txt{'hello'}="Hello ${name}, How are you?";

3. print "<tag>$txt{'hello'}</tag>";

It prints Hello John, How are you? as required, but when 2nd line is read from database, it displays Hello ${name}, How are you?.

Some things I found are:

  1. Locale::Maketext
  2. $string =~ s/(\$\w+)/$1/eeg;
  3. my $string = sprintf 'Say hello to %s and %s', $foo, $bar;

Can someone guide me about how to go about it?


What you're describing is a template. There are lots of template systems on CPAN of varying degrees of complexity. Text::Template and Template Toolkit are a couple of popular ones. You don't want to let your templates access arbitrary variables; that's a security hole. Instead, put the variables they're allowed to access into a hash.

If all you need is a very simple system, you can do something like this:

sub fill_in_template
{
  my ($text, $values) = @_;
  $text =~ s/ \$\{ ( [^}\s]+ ) \} /$values->{$1}/gx;
  return $text;
}

my %txt;
my %values = (name => 'Your Name');

my $template  = 'Hello ${name}, How are you?'; # $name NOT interpolated
$txt{'hello'} = fill_in_template($template, \%values);

print "<tag>$txt{'hello'}</tag>\n";

You might add some error checking in case the template uses a field that's not defined. But if you need something more complicated than that, you're probably better off picking an existing template system from CPAN.

Locale::Maketext is intended for internationalization (so your app can produce output in multiple languages without your translators needing to work on the code directly) and is not the sort of template engine you're looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号