symfony2,templates,include,silex , Silex - How to process template includes separately


Silex - How to process template includes separately

Question:

Tag: symfony2,templates,include,silex

I've got a Twig base template like so:

{% include "./partials/navigation.html" %}

<!-- Main Wrapper -->
<div id="wrapper">
    {% block content %}{% endblock content %}
</div>

I also have a route controller which is outputting the response content to the page using twig:

return template->render('path/to/teplate', args());

where args[] array is all the data needed for this bit: (different on every page)

{% block content %}{% endblock content %}

However my sidebar is being built separately through a menu builder class, and now it needs to render the results of building the menu to my template and populating ./partials/navigation.html.

An easy solution for me is to just append the results of the Menu Builder to the returned response of every controller (I can use a base controller class to do this as this menu appears on every page). However something about this feels unclean as if I have to render the same header/footer every time as well I'll have to be append all 3 outputs to the response. (maybe that is okay?)

Is there a better way of rendering several includes worth of content which each need their own DB lookups and other server-side logic?


Answer:

Yes. They are called sub requests. Read the documentation here.


Related:


Symfony one-to-one, unidirectional relation


symfony2,doctrine2
I have two entities. User and Contact. User and contact have the same property phone_number. I would like to get all contacts with user object if its exists. It is also possible that the same phone number exists in contact table but it doesn't exist in user table. Below is...

Symfony2 creating and persisting entity relationships


php,mysql,symfony2,doctrine2
I have two entities Skin and Email. I want Email to be a part of the Skin entity, however I can't use the console to update schema automatically right now, and that is probably why I can't get the relationship to work. So I want to store all the Emails...

How adapt the path to the previous and next article


php,symfony2
I am looking for a solution to access in the current article to the previous(<<) or the next article(>>) at the end of the page of an article. I thought to get the current paramater of the url with this : {{ dump(app.request.attributes.get('_route_params')) }} and inject in the path with...

Unable to configure Symfony (3rd party) bundle


php,symfony2,rss
I am faily new to Symfony and I am trying to setup a third party bundle that reads RSS feeds and then insert them into database. The third party bundle I am trying to use is called rss-atom-bundle After reading the instructions I can get the RSS feeds however I...

constructor and templates


c++,templates,constructor
I was going through this piece of code where I came across a while calling this code from main #include <iostream> #include <vector> using namespace std; class abc { public: enum example { a=1, b=2, c=3, d=4 }; }; template<typename T> class xyz { public: xyz(T &v,abc::example ex=abc::a):b(v),len(sizeof(T)) { }...

Symfony2/Twig - iterate over select options


php,symfony2,twig
Usual way of displaying select field is to call {{ form_row(form.doctor_service_id, {'attr':{'class':'form-control'}}) }} I would like to perform two things: Check if this field is actually a select field Iterate over every option (value, name). I know how twig iterator works, I just don't know how to access select options...

C++ Will using a pointer to the same function as a template parameter always lead to the same instantiation?


c++,templates,function-pointers
I have a template function taking a function pointer as an argument, and a normal function like so: template <void()> int foo() {static int c = 0; return ++c;} void bar() {} If I understand correctly, two different function pointers can have different binary representations, even if using them would...

Using crontab to call wget every 5 minutes


php,symfony2,crontab,wget
I am working on a project where the wget and crontab are used to run a process in the background. I have a php file named "Hello.php" that I want to run this every 5 minutes. I have found that if I want to have a cron job run every...

How can I access item in parent repeat template while in filter


javascript,html,templates,polymer
<iron-pages> <template is="dom-repeat" items="{{fruit_categories}}" as="category"> <div> <template is="dom-repeat" items="{{all_fruits}}" as="fruit" filter="isThisFruitInTheRightCategory"> <!-- Some more stuff --> <span>{{fruit.weight}}</span> <span>{{fruit.age}}</span> <!-- ... --> </template> </div> </template> </iron-pages> isThisFruitInTheRightCategory: function(fruit){ return fruit.category === /* Q: How do I get the current category? */ } Suppose I...

Deserializing or parse XML response in Symfony2


php,xml,symfony2,deserialization,jmsserializerbundle
I am calling a API method through cURL and I got this response: <?xml version="1.0" encoding="UTF-8"?> <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload"> <id>75080000002s5siAAA</id> <operation>query</operation> <object>User</object> <createdById>00580000008ReolAAC</createdById> <createdDate>2015-06-23T13:03:01.000Z</createdDate> <systemModstamp>2015-06-23T13:03:01.000Z</systemModstamp> <state>Open</state>...

C++: Store pointer to a member function of an object in another object


c++,templates,function-pointers,member-functions
I have a class which shall invoke a function specified by the user on certain occasions. Therefore the class has a method void setExternalPostPaintFunction(void(*function)(QPainter&)); that can be used to "register" a function. This function then will be called on that occasion: class A { public: void setExternalPostPaintFunction(void(*function)(QPainter&)); private: void (*_externalPostPaint)(QPainter&);...

With a OneToMany relation between entities, how create the right queryBuilder with Doctrine (on the Inversed Side entity)


php,symfony2,doctrine2,one-to-many,query-builder
I have these 3 entities in my symfony2.6 project: Compteurs.php class Compteurs { /** * @var \PointsComptage * * @ORM\ManyToOne(targetEntity="PointsComptage", inversedBy="compteurs") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="pointscomptage_id", referencedColumnName="id") * }) */ private $pointsComptage; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\OneToMany(targetEntity="ParametresMesure", mappedBy="compteurs") */ private $parametresMesure; ParametresMesure.php: class ParametresMesure { /** * @var Compteurs...

c++: Passing objects to functions


c++,templates,object
I was going through a code where I encountered some problem and was able to crack this piece of code: #include <iostream> #include <stdint.h> #include <unistd.h> #include <errno.h> #include <vector> #include <sys/types.h> using namespace std; class abc { public: abc(int x,int y) { cout << "x:" << x << endl;...

Passing a struct to a template with extern const. What is the extern for?


c++,templates,struct,const,extern
I am asking myself why the following code works and what the specifier extern does when instantiating baz_instance: struct baz { int value; }; extern const baz baz_instance = {3}; template<baz const& b> int foo(){ return b.value; } int main(){ foo<baz_instance>(); return 1; } Why does the above code compile...

How do I access request parameters in kademi templates?


html,templates,velocity,kademi
I've been developing a website with Kademi and i'm trying to implement a date range search, I've got the date range adding parameters to the URL ?startDate=02/05/15&endDate=12/12/2015 But I don't know how to retrieve these values in kademi templates. How do I do this?...

Explicit instantiation of class template not instantiating constructor


c++,templates,constructor,explicit-instantiation
I'm working on a project in C++ and am having trouble understanding what members of a template class get explicitly instantiated when I explicitly instantiate the template class. I've written the following file, which I then compile using Visual C++ 2008 Express Edition's Release configuration and then pop into a...

Confused about returns in stack template


c++,templates,generic-programming
I'm implementing a generic stack (with an array) in C++ and am confused about what to return in this situation: template <class T> T Stack<T>::pop(void) { if (size != 0) { return items[size - 1]; size--; } else { cerr << "Cannot pop from empty stack." << endl; return ???;...

Symfony change validation message globally


php,symfony2,symfony-2.3
Is there a way to change the basic validation error message to one I need for all entities at once? Currently using Yaml config for every entity, but it's not a way. CF\MyBundle\Entity\User: properties: email: - Email: message: e-mail no válido - NotBlank: message: Campo obligatorio username: -NotBlank: message: Campo...

C++ why does SFINAE fail with only a class template parameter?


c++,templates,c++11,sfinae
I'm using SFINAE in the style of this answer in order to call a generic vector object by using an appropriate member function. For example, the following code calls operator[](int) const first, and if that doesn't exist then operator()(int) const: template<int I> struct rank : rank<I-1> { static_assert(I > 0,...

Call template function for the value of a pointer out of a template function, in C++


c++,templates,pointers,c++11
I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

template template class specialization


c++,templates,template-specialization
I am just learning about Template Template class specialisation. Not a big problem to explain in detail. From my understanding std::uniform_int_distribution is a template whereas std::uniform_int_distribution<Type> is the full specialisation of uniform_int_distribution giving a type. I pass this in the specialisation class template as follows below Main class template <template...

Partial specialization of nested template types produces “internal error” in VC++ 2012 compiler


c++,templates,visual-studio-2012,nested
In the following example, I have an object class which defines a reference class. Both accept mutability as a template argument. In the case that 'obj' is 'Const', I want to disallow a reference of type 'Non_Const'. The example produces the ambiguous message, "An internal error has occurred in the...

Remove automaticaly entity in BD when choice value not selected (or null selected)


php,forms,symfony2,doctrine
I would like to know if symfony/doctrine can manage automaticaly the fact that instead of setting the value of my entity to null it could symply remove it. (by removing it I mean the records where the value equal null) exemple: I have a PICTURE entity linked to a VOTE...

ClassNotFoundException Symfony UserBundle


symfony2,fosuserbundle
I'm developping a website on Symfony2, I want to intergrate FOSUserBundle. I am using Doctrine ORM User class. I've followed the installation steps but I got this error: ClassNotFoundException in AppKernel.php line 21: Attempted to load class "FOSUserBundle" from namespace "FOS\UserBundle". Did you forget a "use" statement for another namespace?...

C++ template template


c++,templates
I'm trying to understand C++ template templates by implementing a generic container class. Here is the code: using namespace std; template <typename T, template <typename STORETYPE> class Container> class Store { public: ~Store() {}; Store() {}; void someFunc( const T & ) {}; //... private: Container<T> storage; }; int main(int...

Overloading Assignment operator in template based class


c++,templates,type-conversion,operator-overloading,template-meta-programming
I am writing a library to support a type of integers which have two template parameters INT_BITS and FRAC_BITS. I was successful in writing a convert function to convert different class types from one to another [ which vary in values of INT_BITS and FRAC_BITS ]. But when I try...

c++: Two ways of declaring multiple templates


c++,templates
I have the following code: template<typename T> struct Pair3{ T first, second; Pair3() : first(T()), second(T()) {} Pair3(T first, T second) : first(first), second(second) {} Pair3(const Pair3<T>& in) : first(in.first), second(in.second) {} template<typename U> void copyFrom(Pair3<U> in); }; template<typename T> template<typename U> void Pair3<T>::copyFrom(Pair3<U> in){ first = in.first; second =...

Django template not found in main project directory error


python,django,templates
I am getting a 'template not found' error, although I've set up a correct template hierarchy (or so I thought) . ├── manage.py ├── twinja │   ├── admin.py │   ├── admin.pyc │   ├── __init__.py │   ├── __init__.pyc │   ├── migrations │   │   ├── __init__.py │   │   └── __init__.pyc │   ├──...

C++ error: deduced conflicting types for parameter 'T' string vs const char *


c++,string,templates,c++11,char
So, I am writing a simple, templated search function for deque container. Here's the code: template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout <<...

How to write and use Monolog handlers and channels


php,symfony2,monolog,symfony-2.6
I have read some docs here but still not clear to me how to write and use a custom Monolog handler and channel. Let me explain a bit what I want to achieve. I have a custom function and I want that log to be logged into a file called...

Symfony/Twig how to render a Route set by anotation?


php,symfony2,routing,twig,url-routing
Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

Symfony Entity query builder that checks for free spots


php,mysql,symfony2,doctrine2,dql
First off all: I know the title isn't helping, but it's the best I can think of. So I've got two entities in Symfony one is called Team and the other one Slot the Slot entity has a name, a start and end date and all that stuff. Besides that...

Mail with html content shows break lines or ignores newlines


email,templates,go,mandrill
I am sending mail to users via mandrill and I using both smtp and mandrill api to send. Content of the mail is rendered go template (.tpl) When I put template like Hi {{.name}}, <br/> This is support. <br/> it sends via mandrill api ok, but is visible when I...

Validation of a form before submission


php,validation,symfony2,form-submit
Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want the...

wkhtmltopdf on openSuSE: cannot connect to X server


php,symfony2,pdf-generation,twig,wkhtmltopdf
I need wkhtmltopdf on openSuSE. I have installed it via the repository. The version is 0.12.1. To render HTML with Symfony, I use the KnpSnappyBundle. By rendering a twig template, I got the following error message: The exit status code '1' says something went wrong: stderr: "wkhtmltopdf: cannot connect to...

pyramid_mako not finding templates. is there a hook to find the directory / file being called?


python,templates,mako
This one is really really buggging me. Will start by saying that everything is working perfectly on my local machine. On the server however, whatever I do ends up in a "Can not locate template for uri: ..." On my local machine I use a Linux VM on Mac OS...

Symfony/Twig radio style formbuilder


php,symfony2,twig,formbuilder
I need to style each of radio button using Symfony form builder. This is my part of my createFormBuilder: ->add('categoryId', 'entity', array( 'class' => 'MyBundle:Category', 'property' => 'name', 'required' => false, 'expanded' => true )) And in my twig template: {% for child in form.categoryId %} <div class="radio i-checks col-md-3">...

Template C++: How to access iterator value for both std::map and std::set?


c++,templates,dictionary,stl,set
I have a specific search function. Because it's used on both std::set and std::map, it was duplicated in our code (not using template). I have to maintain those two functions, and I'd like to move them to a single function using a template (and then have only one search preocedure...

Symfony 2 - Class “Mingle\StandardBundle\Entity\Product” is not a valid entity or mapped superclass


php,symfony2,doctrine,entity,bundle
I created a Product.php file in my bundle Mingle\StandardBundle\Entity like this: <?php namespace Mingle\StandardBundle\Entity; use Doctrine\ORM\Mapping as ORM; /* * @ORM\Entity * @ORM\Table(name="product") */ class Product { /* * @ORM\Column(type="integer") * @ORM\ID * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /* * @ORM\Column(type="string",length=100) */ protected $name; /* * @ORM\Column(type="decimal",scale=2) */ protected $price; /*...

How to re-write templated function to handle type deduction


c++,templates,c++11
So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue <<...

Update session in symfony2 for shoppingg cart


php,symfony2,symfony-2.1,php-5.3,symfony-2.3
I have the following code : public function addAction(Request $request){ //Get submited data // Get Value from session $sessionVal = $this->get('session')->get('aBasket'); // Append value to retrieved array. $aBasket = $request->request->all(); if(count($sessionVal) > 0) { foreach ($sessionVal as $key=>$value) { if($aBasket['product_id'] == $sessionVal[$key]['product_id']) { $sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];...

Wordpress Custom Post type archive display


wordpress,templates,custom-post-type,advanced-custom-fields
I have a custom post type named STORIES. Within that post type, I have categories, so each STORY is also assigned a category like this... Story 1 (assigned category RED) Story 2 (assigned category BLUE) Story 3 (assigned category GREEN) etc. I need to display a page which lists the...

Logs an entire array using Monolog [closed]


php,symfony2,monolog,symfony-2.6
Is there any way to log an entire array using Monolog? I have been reading several docs but didn't find a way to log the entire array in a readable format, any advice? Docs I've read: Monolog, how to log PHP array into console? http://symfony.com/doc/current/cookbook/logging/monolog.html https://www.webfactory.de/blog/logging-with-monolog-in-symfony2 ...

Type function that returns a tuple of chosen types


c++,templates,c++11,metaprogramming
I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

I don't understand how the template function gets to be a friend of the class A::X::Y in the example in [namespace.memdef]/3 in C++14


c++,templates,language-lawyer,c++14,friend
Consider the following code from the example in [namespace.memdef]/3 in C++14: // Assume f and g have not yet been declared. void h(int); template <class T> void f2(T); namespace A { class X { friend void f(X); // A::f(X) is a friend class Y { friend void g(); // A::g...

Unique Entity Error message


api,symfony2,exception-handling,doctrine
I have a user entity which have some unique fields. The code bellow shows you how I defined it. /** * @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE") */ ...... /** * @var string * * @ORM\Column(name="login", type="string", length=255, unique=true) */ private $login; Developping an API, I would like to be able to...

Symfony 2 unable to pass entity repository to form


php,forms,symfony2,runtime-error
I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

Set Auth Token manually for different firewall


symfony2
My application has 2 security firewalls "admin" - used by internal staff "account" - used by customers. Previoly I had one action under the account firewall, the action in the controller looks something like this. $user = //get user somehow $token = new UsernamePasswordToken($user, null, 'account', $user->getRoles()); $this->get('security.token_storage')->setToken($token); With this...

How to use template within Django template?


python,html,django,templates,django-1.4
I have the django template like below: <a href="https://example.com/url{{ mylist.0.id }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... (the actual template is quite big) It should be used 10 times on the same page, but 'external' html elements are different: <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> *django...

Store entity from session doesn't work => $em->persist()


php,symfony2,doctrine2
at first: Sorry for my poor english :-) A beginner need help! I have 3 entities/tables: Tables: contact_person id, title, firstname, surname, adress_id address id, street, zip, city, country_id country (fix values) id, name, code 1, Austria, AT 2, Germany, DE ... Entities: /** * ContactPerson * * @ORM\Table(name="contact_person") *...