프로그래밍/PHP

Smarty에서 javascript 처리 하기 PHP

백룡화검 2009. 10. 21. 19:57
Smarty 메뉴얼을 보면 자바스크립트를 처리하기위해
{literal}{/literal} 구문과 {rdelim}{ldelim}이 준비되어 있다.

그냥 자바스크립트만 있는경우, 자바스크립트안에 스마티 변수를 사용하는 경우
나누어서 테스트해 봤다.
이렇게는 별로 사용되지 않을거지만 필요한 경우에는 유용한듯 하다.

[1.php]
<?php
    require('Smarty/Smarty.class.php');

    $smartyObj = new Smarty;
    $smartyObj->template_dir = "Smarty/templates/";
    $smartyObj->compile_dir = "Smarty/templates_c/";
    $smartyObj->config_dir = "Smarty/configs/";
    $smartyObj->cache_dir = "Smarty/cache/";
    $smartyObj->debugging = TRUE;

    $smartyObj->assign('str', 'Click');
    $smartyObj->display('1.html');       
?>


[1.html]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/html4/strict.dtd">
<html lang="ja" xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=EUC-JP">
    <title>template test</title>
    <script language="javascript">
    <!--
    function display_str()
    {ldelim}
      alert("{$str}");
    {rdelim}
    // -->
    </script>
    {literal}
    <script language="javascript">
    <!--
    function display_str2()
    {
      alert("Good");
    }
    // -->
    </script>
    {/literal}
    </head>
    <body>
        <h1>Template Test Page</h1>
        <div><input type="button" value="{$str}" onClick="display_str();" /></div>
        <div><input type="button" value="{$str}2" onClick="display_str2();" /></div>
    </body>
</html>


위의 html의 자바스크립트 부분을 보면 {literal}{/literal} 구문과 {rdelim}{ldelim} 구문이 쓰여진것을
확인할수 있을것이다. display_str()함수안에 스마티 변수를 사용했는데
{literal}{/literal}로 묶었을경우나 {literal}{rdelim}{ldelim}{/literal}로 묶었을경우
정상적으로 표시되지 않았다
결국 스크립트안의 스마티 변수를 사용하기 위해 {rdelim}{ldelim}만 따로 사용하고
스마티 변수가 사용되지 않는 스크립트는 따로 {literal}{/literal}묶어서 사용한결과
에러 없이 정상적으로 동작하였다.


출처 : http://blog.naver.com/parkjy76/30044584243