如何在Symfony 3中将控制器中的对象发送到视图(Twig)

时间:2017-06-01 13:48:46

标签: php symfony

想象一下,我们的控制器AdvertController.php带有编辑操作public function editAction(Request $request),可将对象$user发送到视图edit.html.twig$user包含许多属性ans返回字符串的方法

public function editAction(Request $request){
$user = new User();
return $this->render('OCPlatformBundle:Advert:edit.html.twig', array());
}

我需要在代码中添加什么?所以在视图中我可以显示值

edit.html.twig

{{ user.name }}

3 个答案:

答案 0 :(得分:1)

它在你已定义的数组()部分。

extension String {
    //  Due to an internal bug in iOS 7.x, 8.1 and 8.2, encoding more
    //  than a few hundred Unicode characters causes various malloc error crashes.
    //  To avoid this issue, batching MUST be used for encoding.
    //      - https://github.com/Alamofire/Alamofire/issues/206
    //      - https://stackoverflow.com/a/44309416/1033581
    func safeAddingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? {
        if #available(iOS 8.3, *) {
            return addingPercentEncoding(withAllowedCharacters: allowedCharacters)
        } else {
            let batchSize = 50
            var batchPosition = startIndex
            var escaped = ""
            while batchPosition != endIndex {
                let range = batchPosition ..< (index(batchPosition, offsetBy: batchSize, limitedBy: endIndex) ?? endIndex)
                guard let percentEncodedSubstring = substring(with: range).addingPercentEncoding(withAllowedCharacters: allowedCharacters) else {
                    return nil
                }
                escaped.append(percentEncodedSubstring)
                batchPosition = range.upperBound
            }
            return escaped
        }
    }
}

然后在树枝上:

$x = 'someothervalue';
$this->render('template', [
    'somekey' => 'somevalue',
    'someotherkey' => $x
]);

答案 1 :(得分:1)

试试这个:

public function editAction(Request $request){
   $user = new User();
   return $this->render('OCPlatformBundle:Advert:edit.html.twig', 
      [
         'user' => $user,
      ]
   );
}

在树枝模板调用函数dump()中,twig渲染所有new User()数据:

{{ dump(user) }}

你可以这样得到它们:

{{ user.name }}
{{ user.soname }}

答案 2 :(得分:0)

试试这个:

public function editAction(Request $request){
    $user = new User();

    return $this->redirect('https://symfony.com/doc/current/index.html');
}