2013-07-22 29 views
2

如何在TWIG文件中使用$ _GET參數,如使用PHP和使用JS進行警報。如何獲得樹枝文件中的參數

URI->?評論=添加...

在TWIG

if($_GET['comment'] == "added"){ 
    ...echo '<script>alert("in TWIG file!");</script>'; 
    } 
+0

我解決了我自己。 {%if app.request.query.get('comment')==''added'%} {%endif%} –

回答

11

希望它會幫助你

{% if app.request.get('comment') == "added" %} 
    <script>alert("in TWIG file!");</script> 
{% endif %} 
+0

謝謝。有用!它簡單的解決方案,但我是新手:) –

0

「正確」的解決辦法是使用你的控制器,提供對嫩枝的功能,而不是在查詢字符串轉換。這將更加強勁,並提供更好的安全性:

控制器:

function someAction() 
{ 
    $params = array('added' => false); 
    if(/* form logic post */) 
    { 
      //some logic to define 'added' 
      $params['added'] = true; 
    } 

    $this->render('template_name', $params); 
} 

觀點:

{% if added %} 
    <script>alert('added');</script> 
{% endif %} 

的理由是,這是更安全(我不能只是觸發警報瀏覽到網址),它維護控制器中的所有業務邏輯,並且還能夠處理任何錯誤 - 例如如果你瀏覽到foo.php?comment = added,並且有一個錯誤,其中你的評論沒有被添加,用戶仍然會收到警報。

1

取決於你真正想實現,顯示確認消息的「Symfony的方式」是使用「提示信息」:

YourController .PHP:

public function updateAction() 
{ 
    $form = $this->createForm(...); 

    $form->handleRequest($this->getRequest()); 

    if ($form->isValid()) { 
     // do some sort of processing 

     $this->get('session')->getFlashBag()->add(
      'notice', 
      'Your changes were saved!' 
     ); 

     return $this->redirect($this->generateUrl(...)); 
    } 

    return $this->render(...); 
} 

你TwigTemplate.twig:

{% for flashMessage in app.session.flashbag.get('notice') %} 
    <div class="flash-notice"> 
     {{ flashMessage }} 
    </div> 
{% endfor %} 

這種方式,您有多個優點:操作防止形式重裝

  1. 重定向後。
  2. 消息不能從外部觸發。
  3. Flash消息只被提取一次。

查看關於此主題的official documentation