[英]Custom Block Magento 2 isnt't working
i wanted to add a new function to \\Magento\\Catalog\\Block\\Product\\View
我想在
\\Magento\\Catalog\\Block\\Product\\View
添加一个新功能
what i did: 我做了什么:
1. app/code/Company/Module
1.
app/code/Company/Module
composer.json composer.json
{
"name": "Company/Module",
"description": "N/A",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0"
},
"type": "magento2-module",
"version": "100.0.2",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Magento\\Cms\\": ""
}
}
}
registration.php 为registration.php
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Company_Module',
__DIR__
);
2. app/code/Company/Module/Product/View
2.
app/code/Company/Module/Product/View
Inside this file: 在这个文件里面:
<?php
namespace Company\Module\Block\Product;
class View extends \Magento\Catalog\Block\Product\View {
private function trySomething()
{
exit('test');return '123';
}
}
?>
3. app/code/Company/Module/etc
3.
app/code/Company/Module/etc
Inside this folder: 在这个文件夹里:
di.xml
Content: 内容:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Product\View" type="Company\Module\Block\Product\View" />
</config>
Also in the folder: 也在文件夹中:
module.xml
Content: 内容:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Company_Module" setup_version="1.0.0">
</module>
</config>
I am tying to call the function over a template, included into product_detail like this: 我想在模板上调用该函数,包含在product_detail中,如下所示:
/**
* Product view template
*
* @var $block \Company\Module\Block\Product\View
*/
?>
<?php echo $block->trySomething(); ?>
This is just another test
The Text "This is just another test" is shown correctly on product_detail but the function won't be called. 在product_detail上正确显示了文本“这只是另一个测试”,但不会调用该函数。
Hope someone can help me. 希望可以有人帮帮我。
I solved it by myself, the problem was that block and layout wasn't in the same module. 我自己解决了,问题是块和布局不在同一个模块中。 I created a
view/frontend/layout
and view/frontend/templates
under app/code/local/Company/Module
this solved it 4 me. 我在
app/code/local/Company/Module
下创建了一个view/frontend/layout
和view/frontend/templates
,这解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.