We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

view file struct, volt Inheritance association

in phalcon project

view file struct

view ----index.volt ----layouts --------test.volt ----test --------test.volt ----shared --------header.volt

in index.volt

{{ partial ("shared/header")}}
<body>
index.content
{{content()}}
</body>
</html>

in shared/header.volt

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <link rel="stylesheet" href="css/global.css" />

{% block csshead %}
{% endblock %}
 </head>

in layouts/test.volt

test controller
{{content()}}

in test/test.volt

testController.testAction
{{content()}}

i want use block csshead in test/test.volt, because i want add css in html head tag. not in html center, not like this:

<link rel="stylesheet" href="css/testController_testAction.css" />
testController.testAction
{{content()}}

i know ,i can like this: view file struct like this:

viewsdir: ----test --------test.volt ----shared --------main.volt

in test.volt

{% extends "shared/main.volt" %}
{% block csshead %}
<link rel="stylesheet" href="css/testController_testAction.css" />
{% endblock %}
testController.testAction
{{content()}}

i don't like this way. have other way to association?



17.8k

my men is ,write testController_testAction.css in action view file. but show page source code, it will show in html head tag ,how to do it?



98.9k

You can introduce a simple class to manage your css assets:

<?php

class Assets {

    protected $_css = array();

    public function addCss($css)
    {
        $this->_css[] = $css;
    }

    public function getCss()
    {
        foreach ($this->_css as $css) {
            Phalcon\Tag::styleSheetlink($css);
        }
    }

}

This class can be registered in the di:

$di['assets'] = function(){
    return new Assets();
};

Then in your views you can add assets using this service:

{{ assets.addCss("some/style") }}

Then in the main template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <link rel="stylesheet" href="css/global.css" />
  {{ assets.getCss() }}
 </head>