有条件地显示HTML表结构时如何避免冗余

问题描述 投票:0回答:1

我的代码正在运行,但我想知道如何让它更优雅,而不是重复整个<tr>内容。

这是代码:

<?php if($condition == true) { ?>
            <tr>
                <?php foreach ( $attributes as $attribute_name => $options ) : ?>
                    <td>
                        content
                    </td>
                <?php endforeach; ?>
            </tr>
        <?php } else { ?>
            <?php foreach ( $attributes as $attribute_name => $options ) : ?>
                <tr>
                    <td>
                       content
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php } ?>

所以,如果条件是true,整个<tr>需要在foreach循环之外,否则它需要在它内部。如何在不重复内容的情况下完成此操作?

php html if-statement tr
1个回答
0
投票

我觉得你有一种优雅的方式来实现这一目标,而不需要进一步改变你需要的结构,但是,作为一种替代方案,你可以使用一些if取决于条件的结果,这将停止重复内容的需要,并帮助您保持DRY标准。

if($condition) { 
  echo '<tr>';
}

foreach ( $attributes as $attribute_name => $options ) {
  if(!$condition) { 
    echo '</tr>';
  } else { 
    echo '<td>';
  }

  //content

  if($condition) { 
    echo '</td>';
  } else { 
    echo '</tr>';
  }

}

if($condition) { 
  echo '</tr>';
}

你也可以使用三元(How to write a PHP ternary operator)条件:

echo ($condition) ? '</tr>' : '';

foreach ( $attributes as $attribute_name => $options ) {
  echo (!$condition) ? '<tr>' : '<td>';

  //content

  echo (!$condition) ? '</tr>' : '</td>';

}

echo ($condition) ? '</tr>' : '';
© www.soinside.com 2019 - 2024. All rights reserved.