douwenan9849 2011-10-25 11:51
浏览 69
已采纳

codeigniter从数据库加载视图

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.

  • 写回答

1条回答 默认 最新

  • duannengling4705 2011-10-25 12:01
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?