dongwenxiu5200 2018-04-01 09:44
浏览 128
已采纳

两个具有相同变量的foreach循环在html中不起作用 - 在slim framework php中使用twig

I'm trying in my code to build a list of courses in an html file (using twig) - but the thing is - I need to use it twice. Once to get the list (and that obviously worked), and once to create a form with multiple checkboxes running in another for loop. I read that the 'unset' function can fix this problem - but it says in doesn't exist in Twig. here's my code:

{% for course in courses %}
   <a href="/course/{{course.id}}">
    <div id="info-box">
    <img src="/views/{{course.image_link}}" alt="" width=95>
    <p style="margin-left: 1rem;">{{course.name}}</p>
    </div>  
   </a>
{% endfor %}

and then I need to write a form:

<form>

    {% for course in courses %}
         <input type="checkbox" name="course" value={{course.id}}>{{course.name}}           
    {% endfor %}
</form>

The second loop doesn't work. I'd love for some help please! :)

and the courses variable comes from a different index file that sends it to an html file.

  • 写回答

1条回答 默认 最新

  • dongqie7806 2018-04-01 15:10
    关注

    I'm not sure why u only can use twig as it would be better to fetch the result in actual array than rather passing the PDOStatement.

    The reason u can only foreach the collection once is because PDOStament is a forward-only result set. This means you can only get the data from this object once.

    To resolve this issue in twig this would mean u need to build an array first and then use that array to display your html

    {% set courses_array = [] %}
    {% for course in courses %}
        {% set courses_array = courses_array | merge([course]) %}
    {% endfor %}
    

    It sure is better to do this in PHP, rather then in twig

    <?php
        $stmt = $pdo->prepare('SELECT * FROM courses');
        $stmt->execute();
    
        $courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $twig->render('courses.twig', [ 'courses' => $courses, ]);
    

    Another solution would be to do the fetch inside twig, to access a constant you can use the function constant

    {% set courses_array = courses.fetchAll(constant('PDO::FETCH_ASSOC')) %}
    

    note: I did not test the last solution

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站