Twig templates engine: get current url - php

How can I get the current URL from a Twig template?
I am using Twig with PHP, without any other framework.

The following works in Silex and most certainly in Symfony2 as they share the Request class (I did not test though) :
{{ app.request.getRequestUri() }}

Finding the current URL
The current URL is supplied by your web server and written to the $_SERVER super-global. Run this small script, <?php echo '<pre>'; print_r($_SERVER);, through your server and root around to find the value(s) you are looking for.
Related questions on this subject:
getting current URL
PHP Determining the current url
How to get URL of current page in PHP
The PHP manual describes the nature of the available $_SERVER values here.
Getting the URL in TWIG
After you have the URL, you need to pass it as a template variable when calling render(...) on the Twig template instance. For example, you might code this.
$current_url = // figure out what the current url is
// pass the current URL as a variable to the template
echo $template->render(array('current_url' => $current_url));
To use the variable in the template, you use the {{ variable_name }} syntax.
Developer's basic Twig documentation
Twig designer documentation for using variables.

Go http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html
or : {{ app.request.getUri() }} for full Uri.

Keeping best practice in mind, at this time you should use Symfony\Component\HttpFoundation\RequestStack.
See http://symfony.com/blog/new-in-symfony-2-4-the-request-stack.
As of Symfony 2.4, the best practice is to never inject the request service, but to inject the request_stack service instead [...]
So in a Silex application it could be achieved with :
app.request_stack.getCurrentRequest.getUri

Here something I found to make it generic with the sliex Framework.
I guess my solution is not perfect but it's get the job done.
in your PHP code add this code :
$app = new Silex\Application();
// add the current url to the app object.
$app['current_url'] = $_SERVER['REQUEST_URI'];
Then in your Twig template you can do
{{ app.current_url }}
Let me know what is the botom line of this method.

Related

Drupal/Twig/Symfony Routing Returns "null" for base_url

I have been researching for almost 2 weeks on for an answer and have finally decided I needed to ask for help. I am quite unfamiliar with PHP/Drupal but has inherited such a project to update and maintain. The project runs on Drupal 8.3.7 and is hosted with IIS 6.2.
For some unknown reason, links in my html.twig files are being returned with a "null" base_url. So for example...
...
will link to "null/home" ... After a lot of hacking and trying to figure out if I could manually set $base_url (not a best practice, I know, but I just needed to see if it was possible), I found two peculiar behaviors:
A. If in the associated controller I create a variable $temp_base_url and hardcode the value "localhost" and attempt to put the following in my html.twig file (where item.url = "/home")...
http://{{temp_base_url}}{{item.url}}
The text between the anchor tag will show up correctly as http://localhost/home while the actual link will direct you to null/home .
B. On the other hand, if I assigned $temp_base_url to equal "http://localhost" and put the following code...
{{temp_base_url}}{{item.url}}
The text between the anchor tag will (aga) show up correctly as http://localhost/home while the actual link will now try to direct you to http://localhost/null/home .
The problem isn't with the global variable $base_url because when I test for this within the Controller, $base_url is setting itself correctly to "localhost" so I suspect Symfony or something else rendering the routes incorrectly (any attempts to use 'path' or 'url' has also resulted in similar null issues).
So my question is: Where are these nulls coming from? How do I get IIS/Drupal to pick up the appropriate base url for routing?
You can use this url('<front>')
{{ url('<front>') }}{{item.url}}

How to get last part of url in blade file (HTML) using laravel 5.2?

I am new to laravel.
I want to get the last part of my url in the blade file(HTML file).
I have done this one using php functionality .
Is there any way I can get it using any laravel functionality .
Below is my code ,its working fine
<?php
$url = url()->current();
echo $end = end((explode('/', $url)));
?>
I have also used this one to get
Request::segment(2)
Here my url is http://localhost/blog/public/user/add-user.
I want to get add-user in the html file.
Thank you
Try this code for getting last value of URL
$uri_path = $_SERVER['REQUEST_URI'];
$uri_parts = explode('/', $uri_path);
$request_url = end($uri_parts);
The answer to your question is: "No there is not any Laravel functionality" or more precisely Laravel helpers for getting the last segment, but fortunately you can just use php. The end has been mentioned and end works on an array, but I don't think it is possible to use directly on Request::segments(). That means you have to put Request::segments() into a variable (like $lastSegment) first and then use end on the variable.
The best and slimmest way I could find to do this is:
{{ basename(Request::url()) }}
Use this in blade, but of course like mentioned before you can add this in the controller or a Laravel view composer.
{{last(request()->segments())}}
If you specifically want the last segment (it may be the 2nd, 3rd, 4th etc) you can use end(Request::segments()) to conistently always get the last segment.
Also, if you don't want to call functions in your templates and be a bit more 'Laravel' why not bind it to your view from the controller?
In your controller:
public function show()
{
return view('your.view')->with('lastSegment', end(Request::segments()));
}
Then in your view you can do this:
<p> The last segment is {{$lastSegment}} </p>
Also, if you want to have $lastSegment be available in all your views without having to code it in all your controllers, look into using Laravel's view composer. Very powerful for making templates.

How to print query result in python/django

I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:
A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.
A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.
I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
app_name/views.py:
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
return render(request, 'socs/detail.html', {'soc': soc})
How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.
I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)
import pprint
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
pprint.pprint(soc)
return render(request, 'socs/detail.html', {'soc': soc})
I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.
The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.
If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send {'soc': soc} to your template as context. Because of this, you should be able to use it in your template. So, in your template (socs/detail.html), just add {{ soc }} somewhere and it should print out the value. The template has full access to the object, so if you wanted something specific, you can also print that instead (like {{ soc.id }}).
If you want to see everything that's in the object without specifying all of the different fields yourself, send OBJECT.__dir__. For example, for this you'd send {'soc': soc.__dir__} as your context. Keep in mind that this likely should not be used for anything but inspection on your part.
If you'd like to learn more about Django's templating, check out the syntax and more.

Laravel Jquery: URLs are being read as "

I'm making an app with Laravel. I have a variable called dataActivity, and I want to use this as an image url. Since Laravel uses {{ URL::asset('path') }} to make a link, I did this:
$('.box').css("background-image", "url('{{ URL::asset('icons/"+dataActivity+".png')}}')");
However, the not found error outputs the link as http://localhost:8000/pictures/"+dataActivity+".png
As you can see, there are &quots where there shouldn't be. Any idea how to fix this?
use
$('.box').css("background-image", "url('{!! URL::asset('icons/"+dataActivity+".png')!!}')");
instead of
$('.box').css("background-image", "url('{{ URL::asset('icons/"+dataActivity+".png')}}')");

ezPublish: Unknown template variable 'view_parameters' in namespace in design/dffestival/templates/page_footer.tpl

We have received below errors on the home page:
eZTemplate # design/dffestival/templates/page_footer.tpl:8[6]:
Unknown template variable 'view_parameters' in namespace ''
In our pagefooter.tpl file have below code:
<div class="attribute-layout">
{attribute_view_gui attribute=$footerNode.data_map.layout view_parameters=$view_parameters}
</div>
We are using eZ Publish Community Project 2012.6 version.
Could anyone explain why I can't retrieve the view_parameters variable and how to do retrieve it?
Thanks
Sunil
Maybe u should start here:
http://www.ezpedia.org/ez/view_parameters
Remember view parameters are by default available only within the
context of the content module and it's views.
All other modules (by default) do not support this feature.
The recommended alternative to view parameters in these situations
would be using get / post parameters instead.
Or here:
https://doc.ez.no/eZ-Publish/Technical-manual/4.x/Templates/Basic-template-tasks/Custom-view-parameters
In some cases $view_parameters won't work, try
$module_result.view_parameters there. So the example above will be:
The color is: {$module_result.view_parameters.color} The amount
is: {$module_result.view_parameters.amount}
Or here (check "$module_result section"):
https://doc.ez.no/eZ-Publish/Technical-manual/3.10/Templates/The-pagelayout/Variables-in-pagelayout
Short answer :
You are trying to retrieve the $view_parameters within the pagelayout (or a template included in it). This is not possible by design and this is completely normal.
Long answer :
View parameters are meant to be used from the views/templates which are used by the content module : for instance, when viewing a content from its alias URL or using its system URL like /content/view/full/2.
They are useful if you want to pass some parameters from the URL to the content view and they are taken into account by the cache system which is a very important thing to keep in mind (this is not the case when using "vanilla" GET parameters).
The main usage is for pagination, for instance : /content/view/full/2/(offest)/2/(limit)10
One of the best practices when developing with eZ Publish (legacy) is to ask yourself : why do you need to retrieve these parameters into your layout ? I guess that you want to control your global layout using them and this is not a good idea.
If you want to control the layout based on something which depends on the content, then I'll suggest to use persistent variables. You will basically use the ezpagedata_set operator in the content/view template and retrieve this value in your pagelayout with ezpagedata() | see https://doc.ez.no/doc_hidden/eZ-Publish/Technical-manual/4.x/Reference/Template-operators/Miscellaneous/ezpagedata_set
Last but not least, remember that the module result is computed before the pagelayout (simply because the pagelayout will include this result using $module_result.content).

Categories