Yekver
Yekver

Reputation: 5185

codeigniter load view from database

I have mail template on different languages, and inside this templates some php variables are using. I have to store templates in DB and before sending a mail, receive template for current language and replace all php vars. While I was doing this with the help of views - there was no probles, but now I don't know how to replace php vars in template? Or maybe there is the better way to solve this problem? I just need to have the ability to edit templates from admin side.

Upvotes: 2

Views: 1108

Answers (1)

fire
fire

Reputation: 21531

Why don't you store the variables in the email template as something non-PHP e.g..

Thank you %name% for registering!

This makes it easy for admin editing.

Then in your code before you send you have an array of all variables to replace...

$template = $this->load->view('email_template.html', '', true);

foreach ($vars as $key => $value) {
    $template = str_replace('%' . $key . '%', $value, $template);
}

Edit

In response to your comment below I would setup the languages in an array and then use PHP in the view to output the correct language, then do the replacement...

// List of message translations
$messages = array(
    'en' => array(
        'thank_you' => 'Thank you %name% for registering!',
        'username_details' => 'Your username is %username%'
    ),
    'fr' => array(
        'thank_you' => 'Merci %name% de l\'enregistrement!',
        'username_details' => 'Votre username est %username%'
    )
);

// Variables to replace
$vars = array(
    'name' => 'John Smith',
    'username' => 'john'
);

// Choose language
$lang = 'en';

// Load the template
$template = $this->load->view('email_template.html', array('messages' => $messages, 'lang' => $lang), true);

// Replace the variables
foreach ($vars as $key => $value) {
    $template = str_replace('%' . $key . '%', $value, $template);
}

email_template.html

<html>
<body>
    <p><?php echo $messages[$lang]['thank_you']; ?></p>
    <hr />
    <p><?php echo $messages[$lang]['username_details']; ?></p>
</body>
</html>

Upvotes: 4

Related Questions