【问题标题】:How to access a specific index in twig?如何访问树枝中的特定索引?
【发布时间】:2015-12-15 23:53:12
【问题描述】:

我正在尝试从我的对象中获取特定值。我只想打印其中的第一个元素,因此我尝试通过在数组位置访问它来将其视为数组。

我也试过用twig属性函数

但是我无法让它工作。

{% for b in dotabets %}    
    {% for t in b.teams %}
       You bet on: {{ t.name[0] }}
    {% endfor %}
{% endfor %}

我试过 {{ t.name|first }} 但它只返回循环中每个项目的第一个字母。

bet.orm.yml

AppBundle\Entity\Bet:
type: entity
repositoryClass: AppBundle\Entity\Repository\BetRepository
table: bets
id:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
fields:
    createdDatetime:
        type: datetime
        column: created_datetime
    betTime:
        type: datetime
        column: bet_time
    status:
        type: integer
        length: 2
    result:
        type: integer
        length: 2
        nullable: true
    homeOdds:
        type: decimal
        scale: 2
    awayOdds:
        type: decimal
        scale: 2
    closedDatetime:
        type: datetime
        column: closed_datetime
        nullable: true
manyToOne:
    game:
        targetEntity: AppBundle\Entity\Game
manyToMany:
    teams:
        targetEntity: AppBundle\Entity\Team
        joinTable:
            name: bets_teams
            joinColumns:
                bet_id:
                    referencedColumnName: id
            inverseJoinColumns:
                team_id:
                    referencedColumnName: id

控制器

class IndexController extends ControllerBase
{
/**
 * @Route("/", name="index")
 * @Template()
 */
public function showMatchesAction()
{
    $betRepo = $this->getEM()->getRepository('AppBundle:Bet');
    $dotaBets = $betRepo->findDota2Matches();
    $csgoBets = $betRepo->findCsGoMatches();


    return [
        'dotaBets' => $dotaBets,
        'csgoBets' => $csgoBets,
    ];
}

【问题讨论】:

  • 你的数组结构怎么样?
  • 它是一个一维数组,我使用的是 symfony2 并将一个实体对象传递给视图
  • 那么为什么要嵌套两个 for 呢?也许你想要 b.teams[0].name?
  • 嘿,感谢您的回答,但我已经尝试过这些解决方案。我添加了额外的代码来画出更好的画面。昨天很晚才发帖抱歉

标签: symfony twig


【解决方案1】:

要访问 twig 中数组上的第一个对象,您可以使用 twig 本身的 'first' 过滤器:

请参阅the Twig documentation about first

基本上你会这样做:

{{ b.teams|first }}

访问数组的第一个值。

您的示例不起作用,因为{{ name }} 没有在任何地方定义为变量。如果它包含在团队中,您宁愿这样:

{{ b.teams[0].name }}

假设您想要收藏中第一个团队的名称,索引从 0 开始

【讨论】:

  • 嘿,感谢您的回答,但我已经尝试了这些解决方案。我添加了额外的代码来画出更好的画面。昨天很晚才发帖抱歉
  • 我不太确定这是如何通过连接表解决的。你可以通过转储调查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2017-06-09
  • 2013-07-05
  • 2012-06-12
  • 2017-06-07
相关资源
最近更新 更多