Access Cookies from Twig? - codeigniter

I have code like this in the base controller:
$this->eu_cookie_preference = $this->input->cookie('eu-cookie-preference');
and in each one of my controller functions I pass this variable to the twig like this:
$this->twig->display('account/my_details.twig', array(
'title' => 'Website | My Details',
'lang' => $this->lang,
'eu_cookie_preference' => $this->eu_cookie_preference,
));
And in the Base Twig I use this variable to do various things.
Is there a way to access the $this->eu_cookie_preference variable from Twig without having to explicitly pass it to each Twig in every controller function?
I have a similar problem with session vars as I have to pass them to each twig in order to access them.

Answer
You can use Twigs addGlobal function to do so. See manual
// Add static text
$twig->addGlobal('text', 'Hello World');
// Add array
$twig->addGlobal('arr', array(1, 2, 3));
// Add objects
$twig->addGlobal('obj', $obj);
You can use these globals just like normal vars:
This is a Text: "{{ text }}",
item in an array {{ arr[0] }},
obj value {{ obj.publicAttr }} or
obj function {{ obj.toHTML5('<img src="" />') }}
Additional information
This way you can implement lazy loading as well. If you load sessions data from your database, that will not be used in every template it can be useful to build a class like this:
class OnDemand {
private $cache;
private $function;
function __construct($function) {
$this->function = $function;
}
private function cache() {
if($this->cache == null) {
$function = $this->function;
$this->cache = $function();
}
}
function __toString() {
$this->cache();
return (string) $this->cache;
}
function __get($key) {
$this->cache();
return $this->cache[$key];
}
function __isset($key) {
$this->cache();
return isset($this->cache[$key]);
}
}
and pass values like this:
$twig->addGlobal('aDataArray', new OnDemand(function(){
// load database data
$data = DB::loadData(...);
return $data;
}));
The function will only be called, when you call the variable in twig.
{{ aDataArray.user.name }}

Related

check if data passed from laravel to vue exists

Sometimes I need to pass data from my controller to the view and sometimes I dont!
But when theres no data passed I get this error:
Undefined variable: tutorial (View:
/var/www/html/resources/views/home.blade.php)
No data example:
public function index()
{
return view('home');
}
Containg data example
public function tutorial()
{
return view('home', ['tutorial' => 'Welcome to myproject, lets get started!!!']);
}
Blade:
beforeMount()
{
let tutorial = {{ var_export($tutorial) }} // ERROR!!
if (tutorial) {
return
}
this.reloadData()
}
I think I can do this way in my index function:
public function index()
{
return view('home', ['tutorial' => []);
}
But its just gross!! Theres anyway to check if data passed from laravel exists in my vue??
Because you cannot just put the Laravel variable in js.
Options to solving the problem included:
Performing an api request for the data using the application
component once it had been mounted.
Attaching the data into the
Javascript context using the blade template.
You can do some thing like this:
<Home tutorial="{{ $tutorial }}"> <!-- make tutorial become to props -->
</Home>
And in your view component:
Vue.component('Home', {
props: [
{
name: 'tutorial', // add this props
default: '',
}
],
beforeMount()
{
if (this.tutorial) { // use like this.tutorial
return
}
this.reloadData()
}
});

ajax routing with symfony

I am using symfony and twig and trying to route to a controller function that exists, using ajax. The route I am trying to get to seems to be appended to the current route (page) that is calling the ajax. What is causing this and what am I doing wrong? I am intermediate at this. Thanks in advance for your efforts.
The ajax looks like;
$.ajax({url: "{{ path('material-stock_check') }}/" + quoteRing.materialId + "/" + quoteRing.gaugeId + "/" + decimal, success: function (results) {
if (results.length === 0) {
quoteRing.findStripWidthAlternates();
}
}});
and the controller looks like
/**
* Check if the strip width is in the Inventory
* #Route("/check/{materialId}/{gaugeId}/{decimal}", defaults={"materialId" = 0, "gaugeId" = 0, "decimal" = 0}, name="material-stock_check")
* #Method("GET")
*/
public function checkStripWidthAction (Request $request, $materialId, $gaugeId, $decimal)
{
$em = $this->getDoctrine()->getManager();
$materialStocks = $em->getRepository('UniflyteBundle:MaterialStock')->findAllByParams(['widthDecimal' => $decimal, 'materialId' => $materialId, 'gaugeId' => $gaugeId]);
if ($request->isXmlHttpRequest()) {
if (null === $materialStocks) {
return new JsonResponse('failure');
}
$results = [];
foreach ($materialStocks as $result) {
$results[] = [
'gaugeId' => $result->getGauge()->getId(),
'materialId' => $result->getMaterial()->getId()
];
}
return new JsonResponse($results);
}
}
When the ajax is called I am getting
No route found for "GET /uniflyte/quote-ring/new/%7B%7B%20path('material-stock_check')%20%7D%7D/93/347/3.45" (from "http://localhost:8088/uniflyte/quote-ring/new/rolled-ring")
The ajax route looks appended to the existing route. What am I doing wrong?
It seems {{ path(...) }} is not being evaluated by twig as #Omar Alves told.
try this, declare a variable in your twig file
<script>
var url = '{{ path("material-stock_check") }}';
</script>
and then use it
Have you declare the path in route file

When using a {domain} wildcard, is there a way to globally set the route( ['domain' => $domain] ) property (not at a function level)

Laravel 5.5
Using a group in RouteServiceProvider for {domain}
I want to be able to call Named Routes in blade without having to pass
public function pageName($domain){
return view('mypage', ['domain'=>$domain,'othervars'=>$domain)])
}
and avoid this mess in blade:
{{ route('nameOfRoute', ['domain'=>$domain]) }}
Instead i would love to simply in my route group set the route(['domain']) property to be $domain and be done with it.
No global way to set it, but instead, wrap the route('name') default helper function with my own helper function, and add the param to the array.
Example function:
function orgRoute($route, $params = [])
{
if (!is_array($params)){
$params = [$params];
}
// Set the domain value if not set, null, or jibberish
if (!isset($params['domain']) || $params['domain']=='{domain}' || $params['domain'] == '')
{
// Instance of App Domain is set in OrgBaseController __construct()
$domain = \App::make('current_domain');
$params['domain'] = $domain;
}
return route($route, $params);
}

Bootstrap Treeview links with laravel 5.4

I am using laravel 5.4 and Bootstrap Treeview.
I have enabled the node text as link:
$('#treeview').treeview({data: data, enableLinks: true});
and in the href field of each node in the Json array I have the laravel route
"{{ route('opciones.create') }}"
Here is where I create the tree (I encode this to Json format in another part of my code)
function buildTree(array $elements, $parentId) {
$branch = array();
foreach ($elements as $element) {
$element['text'] = $element['descripcion'];
$element['href'] = "{{ route('opciones.create') }}";
if ($element['padre'] == $parentId){
$nodes = buildTree($elements, $element['id']);
if ($nodes) {
$element['nodes'] = $nodes;
}
$branch[] = $element;
}
}
return $branch;
}
This is the function in the controller that I need to call which returns a view (a blade file)
public function create()
{ $opcionespadre = Opcion::where('tipo', '=', 'SUBMENU')->get();
return view($this->path.'.create', compact('opcionespadre'));
}
I am using this especific function just to test the tree nodes links, I have other functions in the controller where I need to send a parameter, but first I need to make the link goes somewhere.
When I click on the text of the node, it says that the page I am looking for doesn't exist.
This is what appears in the browser bar:
http://127.0.0.1:8000/{{route('opciones.create')}}
What should I do?
The problem is in this line :
$element['href'] = "{{ route('opciones.create') }}";
Do it like this :
function buildTree(array $elements, $parentId) {
$branch = array();
foreach ($elements as $element) {
$element['text'] = $element['descripcion'];
$element['href'] = route('opciones.create');
if ($element['padre'] == $parentId){
$nodes = buildTree($elements, $element['id']);
if ($nodes) {
$element['nodes'] = $nodes;
}
$branch[] = $element;
}
}
return $branch;
}

Laravel passing data to page

I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}

Resources