简体   繁体   English

检查树枝中for循环内是否存在对象

[英]Check existence of an object inside a for loop in twig

I'm trying to figure out how to check the existance of an object while doing a for loop in twig. 我试图弄清楚如何在树枝中进行for循环时检查对象的存在。

This is how my code looks like. 这就是我的代码的样子。

{% for topic in topics %}
    {% set id = topic.id %}
    {% set ratings = authRatings.id %}

    {% if ratings is defined %}
    {% else %}
    {% endif %}
{% endfor %}

topic.id is the needle and authRatings is a haystack of different objects named after its topic_id. topic.id是针,而authRatings是以其topic_id命名的不同对象的干草堆。 If an object match the topic.id ratings should be defined. 如果对象匹配,则应该定义topic.id评分。

object
(stdClass)[76]
  public '24' => 

object
(stdClass)[77]
      public 'topic_id' => string '24' (length=2)
      public 'user_id' => string '2' (length=1)
      public 'likes' => string '0' (length=1)
      public 'dislikes' => string '1' (length=1)
      public 'time' => string '1348927295' (length=10)
  public '15' => 

object
(stdClass)[78]
      public 'topic_id' => string '15' (length=2)
      public 'user_id' => string '2' (length=1)
      public 'likes' => string '1' (length=1)
      public 'dislikes' => string '0' (length=1)
      public 'time' => string '1348927363' (length=10)

You could write a custom function that does the job. 您可以编写一个自定义函数来完成这项工作。 something like this: 像这样的东西:

$twig = new Twig_Environment($loader);
$twig->addFunction('searchRatings', new Twig_Function_Function('twig_search_ratings'));
function twig_search_ratings($topic_id, $ratings) {
   /* do the search in php */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM