Smarty Template Variable inside Variable - php

I have text this stored in my database:
Your email is: {$email} and your name is {$name}.
$text = get from db this field;
I read this field from the database
I assign with smarty this:
$smarty->assign('text', $text);
$smarty->assign($name, 'maria');
$smarty->assign($email, 'maria#email.it');
and visualize in my html page with this:
{$text}
Result is:
Your email is: {$email} and your name is {$name}.
My problem is Smarty not renders a variable inside a variable.
can someone help me?

You could do this
$smarty->assign('name', 'maria');
$smarty->assign('email', 'maria#email.it');
$smarty->assign('text',$smarty->fetch('string:'.$text));
check out http://www.smarty.net/docs/en/resources.string.tpl for more details
EDIT
If you store your templates in a database, I would recommend you to read about custom template resources http://www.smarty.net/docs/en/resources.custom.tpl

Or if you use Smarty 2
$template = "Your email is: {$email} and your name is {$name}."
require_once( $smarty->_get_plugin_filepath( 'function', 'eval' ));
$smarty->assign('name', 'maria');
$smarty->assign('email', 'maria#email.it');
$compiled = smarty_function_eval(array('var'=>$template), $smarty);

Related

how can i append a $name variable inside a $lang variable?

i have a lang file with lots of pre-made statements
the one i'm working one is used as a template to email users
$lang['ADD_STORE_REQUEST_EMAIL_TITLE'] = " New store has been added";
as you guys can probably guessed, the code above is what would be the email title
my question is, how can i put variable in there? say i wanna have the email title as "hello john, new store has been added"
mail(ADMINISTRATOR_EMAIL,$lang['ADD_STORE_REQUEST_EMAIL_TITLE']"From: no-reply#gmail.com");
i tried adding the 'name' variable before and after the $lang, but it wont work. i tried appending it by name+$lang.... but still wont show up
You can do it like this:
$lang['ADD_STORE_REQUEST_EMAIL_TITLE'] = " New store".$yourVar." has been added";
or
$lang['ADD_STORE_REQUEST_EMAIL_TITLE'] = " New store has been added".$yourVar;
You can use the function sprintf to accomplish this.
Also. To concatenate strings in PHP, you need to use . instead of +
Ex:
mail('email#example.com', sprintf('This is a %s day', 'fine'), sprintf('Hello mr. %s', $name);
This will result in an email being sent to email#example.com with the subject "This is a fine day" and body "Hello mr. {some name from the variable"}

How do i save raw php code to database or text file for sending email message?

Well, In admin panel I'm going to create a custom Email Template. For example... 1) Registration Confirmation 2) Forgot Password etc...
Now let's talk about Registration Confirmation.
After successfully register I'm (admin) sending a confirmation email which I want to edit from admin panel. So my confirmation text is look like this which I save it as .tpt file :
Confirmation text with php code:
<p>Hello $fname $lname, Thanks for your registration in our site Following is your login info.<p/>
<p>Username : <strong>$email</strong> <br/> Password : <strong>$password</strong> </p> <br/> Please click on the link to active your acccount. <a
href='www.//mysite.com/activeAccount.php?code=$key&gonona=$userid'>Active My Account</a> </p>
<p>Thank You.<br/>Support Team <br/>www.//mysite.com/</p>";
In Register.php file I just call this .tpt file when I sending a email message using...
$message = file_get_contents("templates/email_verification.tpt", true);
In admin panel when I want to edit it I just call it with $file_content = file_get_contents($file); function in html textarea field.
So what I want is...
When I send the confirmation message from Register.php page I got text with php code(variable e.g. $fname, $lname) in my email addresss which I don't want. It's should be all plain text. It's should be get the php variable (e. g. $fname, $lname, $email, $password, $key, $userid etc..) value from Register.php page and send it to email address...
How can I do this ? any solution or Idea are Most Welcome :)
Note: Sorry for my bad English language and lack of Php knowledge.
You don't necessarily have to save php variables in your template.
You could also save a template like this:
Hello {{NAME}},
This is your password: {{PASSWORD}}
This is your email: {{EMAIL}}
This way your admin doesn't see weird PHP but a little bit more understandable template.
And when you load the template you can replace the words with your variables at the moment of loading templates.
$message = file_get_contents("templates/email_verification.tpt", true);
$search = array(
'{{NAME}}',
'{{EMAIL}}',
'{{PASSWORD}}',
);
$replace = array(
$fname,
$femail,
$fpassword,
);
$message = str_replace($search, $replace, $message);
Personally I also like to use strtr()
$trans = array(
"{{NAME}}" => $fname,
"{{EMAIL}}" => $femail,
"{{PASSWORD}}" => $fpassword
);
$message = strtr($message, $trans);
The reason why strtr() could be better is if i would enter the following data in form:
name : {{PASSWORD}}
email:test#test.com
password:foobar
With str_replace() If I would enter my name as {{PASSWORD}} the incorrect result would be this:
Hello foobar,
This is your password: foobar
This is your email: test#test.com
This is because str_replace replaces the earlier replaced {{NAME}} with {{PASSWORD}} and again with the foobar!!
With strtr() te resul would be the foollowing (because it only replaces 1 time):
Hello {{PASSWORD}},
This is your password: foobar
This is your email: test#test.com
Which is correct in this case.
You can replace text form $message with the values of your variables.
Try something like this (use | as special character at your template:
$variables = array(
"|fname" => $fname,
"|lname" => $lname,
"|email" => $email,
"|password" => $password
);
$message = str_replace(array_keys($variables), array_values($variables), $message );
Edit: thanks #Valerij for your comment.
it should be like this:
Hello ' . $fname . ', ' . $lname . ',

Using CodeIgniter's word_censor() to replace values in a file

I would like to know if this is the best practice with CI or if there is some better way.
In my project I am sending a confirmation email during the registration process. I have a HTML and TXT template. They both consist of something like this:
Hello {USERNAME}, please click on the activation link below to finish the registration. Link: {LINK}
And in my method I open the templates using the file helper and then replace the {} strings with the actual values using the text helper's word_censor() method like this:
$tmpName = '{USERNAME}';
$tmpLink = '{LINK}';
$name = 'Jon' //retrieved from registration from
$link = 'mysite.com/activate/239dwd01039dasd' //runs the activate function providing the unique ID as an argument
$template = word_censor($template, $tmpName, $name);
$template = word_censor($template, $tmpLink, $link);
return $template
Then I just take the $template and put it inside the CI's mail helper like this:
$this->email->message($template);
What I would like to know is if this is the best way to replace contents of html/txt files with my own values or if there is any better and more efficient way to achieve the same result. I just don't like that I am using the word_censor() function to do something other than what it was intended for..
The better way is to store the email template as a view file.
view
Hello <?php echo $username; ?>, please click on the activation link below to finish the registration. Link: <?php echo $link; ?>
Controller
$data['username'] = 'Jon';
$data['link'] = 'mysite.com/activate/239dwd01039dasd';
$email_template = $this->load->view('myfile', $data, true);
$this->email->message($email_template);
Setting the third parameter on view() to true will return the template rather then echo it out.

PHP/Smarty - Each file has it own language file

I am trying to get each file to have it own language file.
I am using a mix of osDate, SMF and my own code. osDate stores the language in the database, but I am not wanting this, I would like each file to have it own language file, so for example register has it own language file at lang/english/register.php.
I will be using Smarty, which is causing me the headache.
I have the below PHP code working, but don't know how to add or get the language side working.
Here is my current code.
tester1.php
<?php
if (!defined('SMARTY_DIR')) {
include_once('init_test.php');
}
$actionArray = array(
'register' => array('Register.php', 'Register'),
);
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
echo 'test';
} else {
require_once($actionArray[$_REQUEST['action']][0]);
call_user_func($actionArray[$_REQUEST['action']][1]);
}
$t->display('index.tpl');
?>
Register.php
<?php
function Register() {
global $t;
$t->assign('rendered_page', $t->fetch('register.tpl'));
}
?>
index.tpl
{$rendered_page}
register.tpl
Test: {$testlang}<br>
Title: {$title}
Language file - lang/english/register.php
<?php
$lang['testlang'] = 'working';
$lang['title'] = 'This is the title';
?>
So in the example Register needs to pass the language from Register.php to display in register.tpl.
I am aware I can assign each language string in the Register.php file, but I was hoping, I would be able to just assign the who register language file and then just call it at random, without having to assign each language string in Register.php
Any code, tips welcome.
I have tried Googling, but it hasn't come up with much.
You shouldn't pass rendered things into Smarty - you should be passing in an array of strings to use.
register.php
$lang = array(
'test' => "working",
'title' => "This is the title",
);
function Register() {
global $lang;
$t->assign('lang', $lang);
}
index.tpl
Test: {$lang['test']}<br>
Title: {$lang['title']}
Will do what you asked.
However - you don't want to code it like this as it will be incredibly painful to use when you inevitably need to pass in parameters to the strings.
You should define a Smarty function to display translated text with as many variables as needed e.g.
{translate string='Greeting' name=$user.name}
Where the translate function would pull the 'Greeting' string from the list of known strings which would be defined as Hello %name%. It would then replace %name% with the users name to say Hello John etc.

What is the best way to use Email Template in Zend/PHP

I am working on a website where Users create their accounts. I need to send email to users on many oceans. For example when signup, forgot password, order summary etc. I want to use emails templates for this. I need your suggestions for this. I want to use a way that If I change any email template or login in less time and changes.
I have thought about the following way:
I have a table for email templates like this:
id
emailSubject
emailBody
emailType
For example when user forgot password:
id:
1
emailSubject:
ABC: Link for Password Change
emailBody:
<table border=0>
<tr><td>
<b> Dear [[username]] <b/>
</td></tr>
<tr><td>
This email is sent to you in response of your password recovery request. If you want to change your password, please click the following link:<br />
[[link1]]
<br/>
If you don't want to change your password then click the following link:<br/>
[[link2]]
</tr></td>
<tr><td>
<b>ABC Team</b>
</td></tr>
</table>
emailType:
ForgotPassword
Prepare email data:
$emailFields["to"] = "user#abc.com";
$emailFields["username"] = "XYZ";
$emailFields["link1"] = "http://abc.com/changepassword?code='123'";
$emailFields["link2"] = "http://abc.com/ignorechangepasswordreq?code='123'";
$emailFields["emailTemplate"] = "ForgotPassword";
Now Pass the all fields to this function to send email:
sendEmail( $emailFields ){
// Get email template from database using emailTemplate name.
// Replace all required fields(username, link1,link2) in body.
// set to,subject,body
// send email using zend or php
}
I planed to use above method. Can you suggest better way or some change in above logic.
Thanks.
I'd use Zend_View. Store your templates in /views/email/EMAILNAME.phtml, create a Zend_View object with the required email template and pass it the required data.
Off the top of my head, so untested... but something similar should work:
$view = new Zend_View();
$view->setScriptPath( '/path/to/your/email/templates' );
$view->assign( $yourArrayOfEmailTemplateVariables );
$mail = new Zend_Mail();
// maybe leave out phtml extension here, not sure
$mail->setBodyHtml( $view->render( 'yourHtmlTemplate.phtml' ) );
$mail->setBodyText( $view->render( 'yourTextTemplate.phtml' ) );
As previously mentioned, Zend_View is the way. Here is how I do this:
$template = clone($this->view);
$template->variable = $value;
$template->myObject = (object)$array;
// ...
$html = $template->render('/path/filename.phtml');
Use Markdownify to covert to plain text:
$converter = new Markdownify_Extra;
$text = $converter->parserString($html);
Setup mail:
$mail = new Zend_Mail();
$mail->setBodyHtml($html);
$mail->setBodyText($text);
Then setup Transport and send.

Categories