I added the following in view/frontend/layout/catalog_product_view.xml:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        <script src="Vendor_Name::js/my_script.js"/>

And in view/frontend/web/js/my_script.js:

    // ???
], function (
    // ...
) {
    // ...

Here I thought it would suffice to require something like 'Magento_Catalog/catalog/product' to get the product, but it doesn’t work.

If I require 'Magento_Catalog/catalog/product' I get an Uncaught Error: Script error because it doesn’t exist. Magento_Catalog/js/product/view/product-info gives me an Observable object I don’t know how to use. Magento_Catalog/js/product/view/product-info-resolver gives me a callback that I can use to get the product id.

What should I require to get the current product’s informations? I’m trying to determine if the product has a boolean custom attribute set to true.

I’m using Magento 2.4.x.

Thank you.

1 Answer 1


You can pass the value of php variables to a javascript file using requirejs-config.js

Create the files as shown below.


<?xml version="1.0"?>
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="content">
            <block class="Magento\Catalog\Block\Product\View\Description"
                name="product.custom.attr" template="Magento_Catalog::product/view/custom_attributes.phtml"/>


var config = {
    map: {
      '*': {
        'customattr': 'Magento_Catalog/js/customattr'
    shim: {
      'customattr': ['jquery']



$product = $block->getProduct();
$productId = $product->getId();
$sku = $product->getSku();


<script type="text/x-magento-init">
            "customattr": {
                "id": "<?= $productId; ?>",
                "sku": "<?= $sku; ?>"


define(['jquery'], function($) {
    $.widget('custom.attr', {

        _create: function() {
            var id = this.options.id;
            var sku = this.options.sku;


    return $.custom.attr;

Run following commands to render the changes of new files

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
  • Thank you! ____
    – bfontaine
    Jul 2, 2021 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.