我试图在不使用像 Smarty 这样的模板引擎的情况下将表示和逻辑分开。到目前为止,我所拥有的是有效的,但我不确定如何在不将比我想要的更多的 PHP 放入我的演示文稿的情况下做某些事情。例如,现在我有这样的东西:
try {
$query = $conn->prepare("SELECT p.id, p.name, p.description, IFNULL(url, title) AS url, GROUP_CONCAT(c.category SEPARATOR ', ') AS category,
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN categories c ON pc.category_id = c.id
WHERE p.active = 1
GROUP BY p.id");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
echo $e->getMessage();
}
include('templates/product_list_tpl.php');
<div class="card">
<div class="product-list with-header">
<div class="product-list-header center-align">
<h2><?= $header_title; ?></h2>
</div>
<?php foreach ($result as $row): ?>
<!-- Some Product Info -->
Category: <?= $row['category']; ?>
<?php endforeach; ?>
</div>
</div>
在上面的例子中,有些产品有一个类别,有些有多个。它们以逗号分隔的列表很好地显示,但我想将类别名称放入链接中。我知道我可以做类似下面的事情,但对我来说它看起来很乱。
<div class="card">
<div class="product-list with-header">
<div class="product-list-header center-align">
<h2><?= $div_title; ?></h2>
</div>
<?php foreach ($result as $row): ?>
<?php $categories = explode(', ', $row['category']); ?>
<div class="product-list-item avatar">
<img src="img/product/<?= $row['id']; ?>.jpg" alt="<?= $row['title']; ?>" class="square">
<a href="product/<?= generate_link($row['url']); ?>" class="title bold"><?= $row['title']; ?></a>
<p class="caption"><?= $row['caption']; ?></p>
<div class="item-bottom">
<span class="responsive"><?= $row['description']; ?></span>
<p>
Category:
<?php foreach ($categories as $key => $category): ?>
<a href="category/<?= strtolower($category); ?>"><?= $category; ?></a>
<?= (sizeof($categories) > 1 && $key == end($categories)) ? ', ' : ''; ?>
<?php endforeach; ?>
</p>
<p>
<span>Rating: <?= $row['rating']; ?></span>
<span class="right">Rated <?= $row['rated']; echo ($row['rated'] == 1) ? ' time' : ' times'; ?></span>
</p>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
提前感谢您的任何建议。此外,如果有人对我在示例代码中使用的通用分隔格式有任何意见,我很乐意听到。在中断 8 年后,我刚刚重新开始编码。
编辑:添加了缺失的 endforeach 并根据 @Devon 在评论中的建议改进了第三个代码块的缩进。
编辑:我更新了第三个代码块以包含我之前遗漏的 HTML,并添加了实现我正在寻找的输出所需的所有 PHP 功能。它有效,但 IMO 这样做消除了我的小分离。我现在基本上只有一个文件包含我的数据库调用,而另一个文件包含此乱七八糟的文件。我觉得我没有朝着适当的业务逻辑/表示逻辑分离的正确方向前进。
我哪里错了?
最佳答案
冗长、复杂的逻辑,例如:
(sizeof($categories) > 1 && $key == end($categories)) ? ', ' : '';
不应该打扰前端开发人员。 “这行可怕的代码是什么?
它有什么作用?为什么后端开发人员不给我一些更容易使用的东西?” MVC 的部分力量不仅在于关注点分离,而且
还将后端和前端开发人员的工作分开。
代码类似于<?php foreach ($result as $row): ?>不包含关于它正在使用什么的指示。 DIV、P 和 SPAN 也失控了。
这就是我喜欢 View 助手的原因。
我建议:
product_list_tpl.php
<div class="card">
<div class="product-list with-header">
<div class="product-list-header center-align">
<h2><?= $div_title; ?></h2>
</div>
<?= displayItems($items); ?>
</div>
</div>
上面使用的 View 助手:
function displayItems($items)
{
foreach ($items as $item)
{
$categories = explode(', ', $item['category']);
$id = $item['id'];
$title = $item['title'];
$url = $item['url'];
$caption = $item['caption'];
$description = $item['description'];
$rating = $item['rating'];
$rated = $item['rated'];
include('product_list_item_tpl.php');
}
}
product_list_item_tpl.php
<div class="product-list-item avatar">
<img src="img/product/<?= $id; ?>.jpg" alt="<?= $title; ?>" class="square">
<a href="product/<?= generate_link($url); ?>" class="title bold"><?= $title; ?></a>
<p class="caption"><?= $caption; ?></p>
<div class="item-bottom">
<span class="responsive"><?= $description; ?></span>
<p>
Category:
<?php displayCategories($categories); ?>
</p>
<p>
<span>Rating: <?= $rating; ?></span>
<span class="right">Rated <?= $rated; ?> <?= isPluarl($rated)?'times':'time'; ?></span>
</p>
</div>
</div>
上面使用的 View 助手:
function isPlural($number)
{
return $number != 1;
}
function displayCategories($categories)
{
$last = end($categories);
$count = sizeof($categories);
foreach ($categories as $key => $category)
{
$cat = strtolower($category);
$isLast = $category == $last;
include('product_list_category_tpl.php');
}
}
product_list_category_tpl.php
<a href="category/<?= $cat; ?>"><?= $category; ?></a>
<?= ($count > 1 && !$isLast) ? ', ' : ''; ?>
注意我倒转了$key == end($categories)与您之前使用的部分分开 !$isLast并交换了 $key至 $category .这个逻辑仍然让人觉得很脏,因为两个类别可能有相同的名称。可能最好只使用 count($categories)连同$i++决定它是否是最后一个循环。
编辑:
这很好地工作并避免了前面提到的问题,因为它依赖于键而不是值:
function displayCategories($categories)
{
end($categories);
$last = key($categories);
$count = sizeof($categories);
foreach ($categories as $key => $category)
{
$cat = strtolower($category);
$isLast = $key == $last;
include('product_list_category_tpl.php');
}
}
关于php - 保持表示 (HTML) 和逻辑 (PHP) 分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873405/
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
我正在学习http://ruby.railstutorial.org/chapters/static-pages上的RubyonRails教程并遇到以下错误StaticPagesHomepageshouldhavethecontent'SampleApp'Failure/Error:page.shouldhave_content('SampleApp')Capybara::ElementNotFound:Unabletofindxpath"/html"#(eval):2:in`text'#./spec/requests/static_pages_spec.rb:7:in`(root)'
我正在使用Ruby,我正在与一个网络端点通信,该端点在发送消息本身之前需要格式化“header”。header中的第一个字段必须是消息长度,它被定义为网络字节顺序中的2二进制字节消息长度。比如我的消息长度是1024。如何将1024表示为二进制双字节? 最佳答案 Ruby(以及Perl和Python等)中字节整理的标准工具是pack和unpack。ruby的packisinArray.您的长度应该是两个字节长,并且按网络字节顺序排列,这听起来像是n格式说明符的工作:n|Integer|16-bitunsigned,network(bi
我正在尝试将一个简单的CSV文件读入HTML表格以在浏览器中显示,但我遇到了麻烦。这就是我正在尝试的:Controller:defshow@csv=CSV.open("file.csv",:headers=>true)end查看:输出:NameStartDateEndDateQuantityPostalCode基本上我只获取标题,而不会读取和呈现CSV正文。 最佳答案 这最终成为最终解决方案:Controller:defshow#OpenaCSVfile,andthenreaditintoaCSV::Tableobjectforda
我想用Nokogiri解析HTML页面。页面的一部分有一个表,它没有使用任何特定的ID。是否可以提取如下内容:Today,3,455,34Today,1,1300,3664Today,10,100000,3444,Yesterday,3454,5656,3Yesterday,3545,1000,10Yesterday,3411,36223,15来自这个HTML:TodayYesterdayQntySizeLengthLengthSizeQnty345534345456563113003664354510001010100000344434113622315
考虑一下:现在这些情况:#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2我需要用其他字符串输出URL。我如何保证&符号不会被转义?由于我无法控制的原因,我无法发送&。求助!把我的头发拉到这里:\编辑:为了澄清,我实际上有一个像这样的数组:@images=[{:id=>"fooid",:url=>"http://