0

这让我发疯,我创建了一个带有助手的模块:

    namespace MyNamespace\MyModule\Helper;

    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
        protected $registry;

        public function __construct
        (
            \Magento\Framework\Registry $registry,
        \Magento\Eav\Api\AttributeSetRepositoryInterface $attributeSet
        ) {
            $this->registry = $registry;
        $this->attributeSet = $attributeSet;
        }

        public function getTitle()
        {
            $this->product = $this->registry->registry('product');
        $product_name = $this->product->getName();
            $attributeSetRepository = $this->attributeSet->get($this->product->getAttributeSetId());
        if ($attributeSetRepository->getAttributeSetName() == "Default Engine Component"){
        $engine = $this->product->getAttributeText('engine_select');
        if (!is_array($engine)){
            return "$engine $product_name";
        }
        }
            return $product_name;
        }
    } 

......这可以正常工作。然后我将以下内容添加到:

/app/design/frontend/vendor/theme/Magento_Catalog/layout/catalog_product_view.xml

<referenceBlock name="page.main.title">
    <action method="setPageTitle">
        <argument name="title" xsi:type="helper" helper="MyNamespace\MyModule\Helper\Data::getTitle"></argument>
    </action>
</referenceBlock>

...但它在产品页面上没有任何改变。我知道它被调用了,因为我可以回显变量并且它们显示在页面顶部,但似乎 XML 并没有像我希望的那样做。

有人有什么想法吗?

4

1 回答 1

2

因此,尝试了多种变体来实现我想要的,但最后,我在Magento_Catalog/templates/product(在我的主题中)创建了一个模板,该模板基于magento-theme title.phtml然后修改了布局文件page.main.title中的块。catalog_product_view

模板代码可能看起来有点奇怪(getAttribute然后getAttributeText),但没有错误处理getAttributeText和 with getAttribute,如果一个属性有多个值,它会在一个字符串中返回,而不是像getAttributeText. 如果我可以通过检查正在使用的属性集来确保该值始终存在,那就更好了,但是虽然getAttributeSetId它是产品模型的一部分,但它在拦截器中不可用,product/view而且我已经放弃尝试弄清楚这一切是如何运作的!

无论如何,这花费的时间比我愿意承认的要多得多,所以这里是代码,希望它对某人有所帮助!

模板:

<?php
$product = $block->getProduct();
$product_name = $product->getName();
$attr_exists = $product->getResource()->getAttribute('attr_code');
$title = $product_name;
$cssClass = $block->getCssClass() ? ' ' . $block->getCssClass() : '';

if ($attr_exists){
  $attr_name = $product->getAttributeText('attr_code');
  if (!is_array($attr_name)){
    $title = "$attr_name $product_name";
  }
}

?>
<?php if ($title): ?>
<div class="page-title-wrapper<?= /* @escapeNotVerified */ $cssClass ?>">
<h1 class="page-title"
    <?php if ($block->getId()): ?> id="<?= /* @escapeNotVerified */ $block->getId() ?>" <?php endif; ?>
    <?php if ($block->getAddBaseAttributeAria()): ?>
        aria-labelledby="<?= /* @escapeNotVerified */ $block->getAddBaseAttributeAria() ?>"
    <?php endif; ?>>
    <?= /* @escapeNotVerified */ $title ?>
</h1>
<?= $block->getChildHtml() ?>
</div>
<?php endif; ?>

布局:

<block name="page.main.title" class="Magento\Catalog\Block\Product\View" template="Magento_Catalog::product/product-h1.phtml" />
于 2018-05-18T19:00:29.513 回答