dream_life5200 2012-03-30 09:21
浏览 231
已采纳

PHP - 在循环中使用include的替代方法

I have a chunk of HTML code (with some PHP vars echoed inside of it) that I need show on multiple times (inside a loop) AND on multiple pages.

So how to keep it DRY?

My ideas admittedly were not brilliant:

  • Putting it in a separate file and including - but then I'll do an include inside a loop and it showed like bad practice.

  • Putting it in a function - but then I have to make variables global plus it just doesn't look to me like functions are meant for such usage.

Is there a better way? Is this where maybe OOP has a solution? (I run php 5.3)

  • 写回答

3条回答 默认 最新

  • drgwsx8405 2012-03-30 09:26
    关注

    Use templates.

    Just write your loop inside of the template, as well as all other presentation code.

    <h1>Some list</h1>
    <ul>
    <?php foreach($data as $row): ?>
      <li><?=$row['name']?> whatever your block code goes here</li>
    <?php endforeach ?>
    </ul>
    

    so, no need to include anything at all.

    For the multiple pages you may wish to make a helper function, called from the template.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分