How to add assets (CSS, JS, etc.) to a Phalcon project?

by cortez.connelly , in category: PHP Frameworks , 2 years ago

How to add assets (CSS, JS, etc.) to a Phalcon project?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 2 years ago

@cortez.connelly 

To add assets to a Phalcon project, follow these steps:

  1. Create a directory for your assets (e.g. public/assets).
  2. Place your CSS, JS, images and any other asset files into this directory.
  3. In your view file, use the public_url and javascript_include_tag/stylesheet_link_tag helpers to generate URLs to your assets. For example:
1
2
3
4
<head>
   <?php $this->assets->outputCss('main') ?>
   <?= $this->tag->javascriptInclude('js/jquery.js') ?>
</head>


  1. Create an assets manager service in your project's services.php file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use PhalconAssetsManager as AssetsManager;

$di->setShared('assets', function() {
    $assets = new AssetsManager();

    // Set the assets base path
    $assets->setOptions([
        'sourceBasePath' => __DIR__ . '/../public/assets/',
        'targetPath' => __DIR__ . '/../public/assets/',
        'targetBasePath' => '/assets/',
    ]);

    // Add CSS assets
    $assets->addCss('css/bootstrap.min.css');
    $assets->addCss('css/main.css');

    // Add JS assets
    $assets->addJs('js/jquery.min.js');
    $assets->addJs('js/bootstrap.min.js');

    return $assets;
});


  1. Optionally, you can use groups to group related assets together:
1
2
$assets->collection('footer')->addCss('css/footer.css');
$assets->collection('header')->addCss('css/header.css');


  1. In your layout file, output the assets using the outputCss and outputJs methods:
1
2
3
<?= $this->assets->outputCss('header') ?>
...
<?= $this->assets->outputJs('footer') ?>