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

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里