0

I defined a function in a block class as below to return the contents of an entire custom JS file, the path of which is stored in $absolute_custom_js_file_path . What is the right PHP function to be used inside the return statement so that my phtml file would get all the JS file contents? Thanks for the help.

    public function getAllPagesJSContent() {
    // Code to get the absolute path to the media directory.        
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
    $mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();

    // Code to get the absolute path to the custom JS file.
    $absolute_custom_js_file_path = $mediaPath . 'pmm-custom/allpages.js';
    return __('What PHP function to use to read and return the contents of the JS file)');
}

Here is the phtml:

<?php echo $block->getAllPagesJSContent(); ?>

  • 1. Please dont use ObjectManager if You really dont need do it. Use __construct. 2. What You exactly need? Just display js content for customer or something else ? – Konrad Siamro May 12 '20 at 10:33
  • Sure, I will definitely replace object manager by employing dependency injection. Yes, for now, I just want to output it inside the head section within <script></script> so that it is visible only in the viewsource not to the visitors. – CodeForGood May 12 '20 at 10:43
  • But whats Your purpose? It is a bit weird way for attach script to page. You can add js to specific page by xml layouts. – Konrad Siamro May 12 '20 at 10:47
  • I need this script available across the site, and the getAllPagesJSContent() is going to be called by another custom JS file. – CodeForGood May 12 '20 at 10:50
  • Maybe I dont understand Your purposes but it looks like dirty workaround. magento.stackexchange.com/questions/131056/… imo it should solve Your needs – Konrad Siamro May 12 '20 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.