首页 文章

使用智能模板显示尺寸图像

提问于
浏览
0

我正在使用 smarty 模板动态渲染页面;这就是我在 php 文件中分配变量的方式:$imgsrc1,$imgsrc2,$imgsrc3 包含上传图像文件的位置

$smarty->assign('foto1', $imgsrc1);
$smarty->assign('foto2', $imgsrc2);
$smarty->assign('foto3', $imgsrc3);

在模板文件中,我以这种方式使用它们:

<img src='{$foto1}' border='1' width="230" height="250">
<img src='{$foto2}' border='1' width="630" height="850">
<img src='{$foto3}' border='1' width="130" height="150">

我知道这不是显示图像的理想方式。这样做了;只是没有采取高度和宽度;显示原生高度和宽度。我想我应该使用{。 5},但我不知道如何分配然后使用它在模板中显示。

编辑:请注意,不仅仅是图像的显示,我想控制它们的大小。例如,image1 必须具有 230 x 250 的固定大小,而 image2 必须具有 630 x 850 的固定大小,而 image3 必须具有 130 x 150 的固定大小,而与上载文件的原始属性无关。

2 回答

  • 0

    在 PHP 循环中像这样:

    $newArray = array();
    $imagesArray = [$imgsrc1,$imgsrc2];
    for(i = 0;i<count($imagesArray);$i++;){
       list($width, $height) = getimagesize($imgsrc1);
        $newArray[$i]['src'] = $imgsrc1;
        $newArray[$i]['width'] = $width;
        $newArray[$i]['height'] = $height;
    }
    $smarty->assign('imagesArray', $newArray);
    

    然后在这样的 smarty 循环中:

    {foreach from=$imagesArray key=myId item=i}
            <img src='{$i.src}' border='1' width="{$i.width}" height="{$i.height}">
        {/foreach}
    

    没有测试代码,可能会有一些小的语法问题。

  • 0

    您已经使用\ {html_image }暗示了最简单的方法。

    如果你不想改变你的 PHP 代码......

    $smarty->assign('foto1', $imgsrc1);
    $smarty->assign('foto2', $imgsrc2);
    $smarty->assign('foto3', $imgsrc3);
    

    ...then 您可能只想将智能模板更改为......

    {html_image file=$foto1}
    {html_image file=$foto2}
    {html_image file=$foto3}
    

    这简化了您的任务,因为您可以让 smarty 完成工作以发现实际的图像大小。

    生成的 html 代码看起来像这样:

    <img width="230" height="250" alt="" src="/path/to/your_image1.jpg">
    <img width="630" height="850" alt="" src="/path/to/your_image2.jpg">
    <img width="130" height="150" alt="" src="/path/to/your_image3.jpg">
    

    如果你想对输出有更多的控制,你必须将图像处理移动到 php。如果这是你想要的,请与我联系。

    ****更新

    由于您明确表示要基本控制宽度和高度而不检查源图像尺寸,因此您不必分析图像,这就是{html_image}所做的。相反,只需将尺寸变量推入模板,也许就像这样。

    PHP 代码:

    $arr = array(
        0 => array(
            'path' => '/path/to/your_image1.jpg',
            'wdth' => '230',
            'hght' => '250'
        ), 
        1 => array(
            'path' => '/path/to/your_image2.jpg',
            'wdth' => '630',
            'hght' => '850'
        ), 
        2 => array(
            'path' => '/path/to/your_image3.jpg',
            'wdth' => '130',
            'hght' => '150'
        )
    );
    
    $smarty->assign('images', $arr);
    

    聪明的模板代码:

    {foreach $images as $img} 
        <img src='{$img.path}' border='1' width="{$img.wdth}" height="{$img.hght}">
    {/foreach}
    

    请记住,我在这里使用了一个数组,以便更好地可视化依赖关系。这当然可以在不使用阵列的情况下完成。

相关问题