Magento2 – How to Use Tabs Widget

jquerymagento2tabswidget

I am stuck in using tabs widget in Magento2. I have not found any resource that teaches about this. The only resource is this: DevDocs But this is useless. It is only a reference of options and methods, but not how to use it.

I have this in attributes.phtml of my custom theme:

<div id="Tabs1">
    <ul>
        <?php $count = 0 ?>
        <?php foreach ($_additional as $_data): ?>
            <li data-role="title"><a href="#tabs-<?php echo ++$count ?>"><?php echo $block->escapeHtml(__($_data['label'])) ?></a></li>
        <?php endforeach; ?>
    </ul>
    <?php $count = 0 ?>
    <?php foreach ($_additional as $_data): ?>
        <div id="tabs-<?php echo ++$count ?>" data-role="content">
            <p><?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></p>
        </div>
    <?php endforeach; ?>
</div>

<script type="text/javascript">
require([
    'jquery',
    'jquery/ui'
], function($){
    $(function () {
        $("#Tabs1").tabs();
    });        
});
</script>

But that does not work. Can you show me where is the error, please?

Thanks
Jaime

Best Answer

You have error on the page because you miss your tabs widget in dependencies list (at list if you want to use Magento's tabs widget).

Correct:

require([
    'jquery',
    'mage/tabs'
], function($){

But I can suggest more convenient way:

<div data-mage-init='{"mage/tabs":{}}'>
    <ul>
        <?php foreach ($_additional as $_key => $_data): ?>
            <li data-role="title"><a href="#tabs-<?php echo $_key ?>">...
        <?php endforeach; ?>
    </ul>
    <?php foreach ($_additional as $_key => $_data): ?>
        <div id="tabs-<?php echo $_key ?>" data-role="content">
            ...
        </div>
    <?php endforeach; ?>
</div>

mage/tabs.js will be loaded by Magento's App and initialized on needed element.

Related Topic