Different views according to url in symfony2? - symfony

Suppose in my twig file I have following codes. Everything is working fine how to have different view if I click page number in Pagination tab.
When I click page no2 it should have different output. Eg
<p> This is page no2</p>
My url
http://localhost/project/web/app_dev.php/funfact/2
When I check current url using
{% if app.request.attributes.get('_route') == 'funfact/2' %}
</p> this is page no 2</p>
{%endif%}
it is not giving the above output.
How do I match current url with http://localhost/project/web/app_dev.php/funfact/2
Also in Phpstorm its giving me Alias 'Sensio\Bundle\FrameworkExtraBundle\Configuration\Route' is never used
In my twig view.html.twig
This is page 1
<div class="row">
<ul class="pagination pagination-lg">
<li>«</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>»</li>
</ul>
</div>
routing.yml:
funfact:
path: /funfact/{page}
defaults: { _controller: HomeBundle:FunFact:funView, page: 1 }
Controller Class
class FunFactController extends Controller
{
/**
* #Route("/funfact/{page}"),defaults={"page" = 1})
*/
public function funViewAction($page)
{
return $this->render('HomeBundle::funfact.html.twig');
}
}

Try this code
{% if 'funfact/2' in app.request.uri %}
</p>this is page no 2</p>
{% endif %}

Related

flask-bootswatch: css is not loading in "/" paths

While working on a project which I build using Flask and a Bootswatch theme which is a books website, letting users to register, log in and then search for books and when a users selects one of results it gives information about that book,but I found out that information page which I implemented wasn't loading the styling of page, contrary to all other pages which are working fine.
My application.py for information page is:
#app.route("/book/<isbn>")
def book(isbn):
# getting the book from database
book = db.execute("SELECT * FROM books WHERE isbn=:isbn", {"isbn": isbn}).fetchone()
if book is None:
return render_template("failure.html", error="Please enter some query", code = "403!")
db.commit()
# giving details to webpage
return render_template("book.html", book = book)
as you can see I am using ISBN (International Standard Book Number), as a path for different books because each book has unique ISBN, thus I assume it is great for making links to different individual book page.
and book.html looks something like this:
<!-- further exptending the layout page -->
{% extends "layout.html" %}
<!-- further extending the title -->
{% block title %}
Books: Book Page
{% endblock %}
<!-- further extending the body -->
{% block body %}
<h3 align="center"> {{book.title}} by {{book.author}}</h3>
<div>
<li>
Title: {{book.title}}
</li>
<li>
Author: {{book.author}}
</li>
<li>
ISBN: {{book.isbn}}
</li>
<li>
Year: {{book.year}}
</li>
</div>
{% endblock %}
Please figure out where I am going wrong.
Problem is in first line here in application.py it should be
#app.route("/<isbn>")
because /book/<isbn> loads css from /book/static/bootstrap.min.css.

Fetching objects from database in Symfony 2.7.3

I'm trying to show some object properties stored on the database. I've got the controller, the Entity, and the view. I'get no excepctions but I can't see the object properties.
Controller:
/**
* #Route ("/ov", name="ov")
*/
public function select(){
$a=$this->getDoctrine()->getRepository('AppBundle:PC')->find(2);
if(!$a){
throw $this->createNotFoundExcepction('No PC');
}
return $this->render('PcDetailed.html.twig', array('pcs' => $a));
}
View:
{% extends 'master.html.twig' %}
{% block divCentral %}
<div class="row">
<p>Nom del pc</p>
<div class="small-6 small-centered columns">
{% for pc in pcs %}
<p>{{ pc.nom }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
Edit:
Finally, like Chris says, the problem is 'cause on the View I'm using I'm trying to iterate is an object, not an array. That's why doesn't work.
That's the way I must do it:
return $this->render('PcDetailed.html.twig', array('pcs' => array($a)));
In your controller you get the PC with id 2 and pass it to the view.
In the view you are now trying to iterate over this object. I have no idea what TWIG does when you try to iterate over something that is not an array or a collection but maybe it just fails silently.
To fix it, change your controller code to send an array to the view:
return $this->render('PcDetailed.html.twig', array('pcs' => array($a)));

Symfony2 - Display data on same page

I am having a little trouble displaying data on the same page again. I have a simple view
{% block main %}
<div class="col-md-4">
<section class="panel panel-default">
<div class="panel-body">
<form action="{{ path('NickAlertBundle_tsubmit') }}" method="post" enctype="multipart/form-data" class="terminalForm" id="terminalForm">
<div class="row">
<div class="col-md-12">
<input type="text" class="addMargin" id="terminal_command" name="terminal_command" placeholder=">">
</div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-default" id="terminal_submit" value="Submit">
</div>
</div>
</form>
</div>
</section>
</div>
<div class="col-md-8" id="terminal-window">
</div>
{% endblock %}
So on that view I display a form. The user enters some data and then I want the response display in the terminal-window div. So I have set up routes
NickAlertBundle_terminal:
pattern: /terminal
defaults: { _controller: NickAlertBundle:Alert:terminal }
methods: [GET]
NickAlertBundle_tsubmit:
pattern: /terminal
defaults: { _controller: NickAlertBundle:Alert:tcreate }
methods: [POST]
The GET simply renders the initial page, the POST controller is doing
public function terminalAction()
{
return $this->render('NickAlertBundle:Page:terminal.html.twig');
}
public function tcreateAction(Request $request)
{
try {
$terminal_command = strtoupper($request->get('terminal_command'));
$uapiService = $this->container->get('alert_bundle.api_service');
$commandData = $uapiService->terminalService($terminal_command);
return $this->render('NickAlertBundle:Page:terminal.html.twig', array(
'data' => $commandData,
));
}catch (Exception $e) {
}
}
Is this the correct way to do it? Reason I ask is because if I add the following to my div in the view
{% for d in data %}
{{ d }}
{% endfor %}
I obviously get the following error
Variable "data" does not exist in...
So how can I render the data that is returned from the form submission?
Thanks
This is because Twig expects data to be passed to the template the first time the page is rendered (which is handled by the initial GET controller). To remedy the issue, you need to check to determine if data has been defined.
I would do something like this:
{% if data is defined %}
{% for d in data %}
{{ d }}
{% endfor %}
{% endif %}
Now, when the form initially loads but is empty, Twig first checks to see if the variables was passed to it, and since it doesn't, it just skips the for loop altogether.
The other option would be to simply pass an empty array in your first controller. I would view it as less desirable unless you are persisting data and at that point it would be practical anyway.

No more routes available after Twig's render() function

I’m facing a weird behavior from Symfony 2.5.5 (PHP 5.6.1), more specifically Twig. Here is a fragment of my template layout:
<nav>
{% render controller('SGLotteryGameBundle:Home:lastDraw') %}
<ol class="breadcrumb">
<li>{{ 'SuperWinner'|trans }}</li>
{% block bc %}{% endblock %}
</ol>
</nav>
This template worked fine until I added the render call. After that, Symfony reported:
An exception has been thrown during the rendering of a template
("Unable to generate a URL for the named route "sg_lottery_home" as such route does not exist.")
in /home/kevin/Prog/PHP/SG2/src/SG/Lottery/GameBundle/Resources/views/layout.html.twig at line 70.
Of course, the sg_lottery_home is defined and works well without the render block. If I comment the path generation of this route, the immediate next one fails. Routes before the tag are rendered without any issue.
Here is the SGLotteryGameBundle:Home controller:
<?php
namespace SG\Lottery\GameBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
class HomeController extends Controller
{
/**
* #Template
*/
public function indexAction()
{
return [];
}
public function lastDrawAction()
{
return new Response('Dummy');
}
}
I tried replacing {% render ... %} by {{ render(...) }}, without any change.
Important note: it only happens when I’m logged in.
Apparently, it was caused by JMSI18nRoutingBundle generating an error while retrieving the user's locale: the available locales were en and fr and the user's locale fr_FR. I have no idea how the {{ render(...) }} call interacted with that.

Handling duplicates in Twig templates

I have this code in my Twig template:
{% for entity in entities %}
<ul>
<li>{{ entity.getName }} | Editar - Eliminar
{{ render(controller('ProductBundle:DetailGroup:index', { 'parent_id': entity.getId })) }}
</li>
</ul>
{% endfor %}
<dl class="sub-nav">
<dd>Add new</dd>
</dl>
<script>
$(function() {
$("#detail_group_create").click(function() {
loadCenterLayout(Routing.generate('detail_group_new'));
});
});
</script>
Because I'm calling this {{ render(controller('ProductBundle:DetailGroup:index', { 'parent_id': entity.getId })) }} I get the Add new link twice. I don't want to create a new function to handle the same, how did yours deal with this? Any tips or advice?
If I understood you correctly, you want to have index with dynamic center part of the layout. You either have to have:
separate controller functions or
single controller function but some GET/POST parameter and big IF/ELSE branching.
In second case you must not rely on #Template annotation (in case you use them) but rather on manually calling appropriate template render based on which branch you're in.
Did I get your issue right?

Resources