I'm moving some of my view strings to config because I want to use the same code for similar sites, and I'm wondering if there's a way to avoid a call to Config:: or Lang:: on every runtime.
<h1>{{ Config::get('siteName') }}</h1>
blade makes in into
<h1><?php echo Config::get('siteName'); ?></h1>
But I want it to be just plain HTML like
<h1>MySite</h1>
My approach is trying to make this when Blade compiles the views into plain PHP / HTML , is there any built-in way to do this? I've tried with some Blade methods like #string with no results
Thanks
On your controller do this
$siteName = Config::get('app.siteName');
View::make('xxx', array('siteName' => $siteName))
for example
And you will be able to retrieve te variable siteName on your view with only
{{$siteName}}
Hope this will help (Or maybe I doesn't understand the problem)
OK solved it by extending Blade
I created a blade tag such as
#hardcodeConfig('siteName')
And in my blade_extensions I did this:
Blade::extend(function($view, $compiler)
{
$pattern = $compiler->createMatcher('hardcodeConfig');
$matches = [];
preg_match_all($pattern, $view, $matches);
foreach($matches[2] as $index => $key){
$key = str_replace([ "('", "')" ], '', $key);
$configValue = \Config::get( $key );
$view = str_ireplace($matches[0][$index], $configValue, $view);
}
return $view;
});
This does exactly was I was looking for, I created one for Config and another for Lang
Related
Is it possible to make an API which prints database records like this: http://localhost:8000/products/?compare=1-2-N...(1,2,N) product id's. I have succeeded printing only one record. My route:
$router->get('products/{id}','ProductController#getProduct');
and my controller:
public function getProduct($id){
$tlt_products = DB::table('tlt_products')->find($id);
$tlt_products_features_id = DB::table('tlt_product_features')->where('product_id', $id)->get()->pluck('feature_id');
$tlt_features = DB::table('tlt_features')->whereIn('id', $tlt_products_features_id)->get()->groupBy('feature_group');
$tlt_feature_groups = DB::table('tlt_features')->groupBy('feature_group')->get()->toArray();
return response()->json([
'product' => $tlt_products,
'product_features' => $tlt_features,
'feature_groups' => $tlt_feature_groups
]);
}
could you please help me printing array of records using route like this:
http://localhost:8000/products/?compare=1-2-3...-N
Yes, it can be possible. You can try to pass a pattern through get and parse it to retrieve the information your need, but why don't you use a simple way to do that such as:
$router->get('products/{begin}/{end}','ProductController#getProduct');
every thing you want it possible just design it well and in your controller, you have
public function getProduct($begin,$end){
...
}
I finally managed to solve this issue using $tail = $request->tail;method and adding requested id like this on my form action
#php
$tail = basename(request()->path());
$text = (string)$tail;
#endphp
<form action="/product-compare/{{$text}}-{{ $product['id'] }}" method="post">
I'm trying to figure out a way that I can pass PHP code directly within the templates in TWIG without having to create separate extensions for each function. Basically a simple function that could parse out the PHP and run the code in the template.
Example:
$function = new Twig_SimpleFunction('php_parse_function', function () {
//parse php code here
});
$twig->addFunction($function);
Use-case Example:
{{ php_parse_function | php code }}
The problem with doing something like this is that I would have to include an entire code-block in a string, which is to print html encapsulated in another string, which will have class/other-attributes in another layer of quotes.
Example:
{{php_parse_function | "echo '<section class=\'Yo\' id=\'2\'>'</section>" }}
So is there a workaround for something like this?
EDIT (after question edit)
No, It's not possible to execute php code directly from Twig. You can create filters or functions and pass strings as arg.
How? This way (orginal answer):
Anywhere inside the controller you're loading Twig:
// ...
$twig = new Twig_Environment($loader, $params); // load Twig env
$tsf = new Twig_SimpleFunction('fooTwig', function ($str) {
return eval($str);
});
$twig->addFunction($tsf);
// ...
Then:
{{ fooTwig('echo "Hello, World! What kind of sorcery is this? F in hex is "; echo hexdec("F");') }}
And remember you can use filters too!
Controller:
// ...
$twig = new Twig_Environment($loader, $params); // load Twig env
$tsf = new Twig_SimpleFilter('fooTwig', function ($str, $fn) {
$args = array_merge(array($str), array_slice(func_get_args(), 2));
return call_user_func_array($fn, $args);
});
$twig->addFilter($tsf);
// ...
Then:
{{ 'F'|fooTwig('hexdec') }}
If you are using Symfony2 or any other framework, is the same logic. You should just investigate where to add the Twig simple function/filter.
struggling to figure out how to best do what I would normally in simple PHP.
I have the following URL:
/viewbuild/2
The aim is that viewbuild is the view and 2 is the id of the database row.
Normally It would simply be:
$id = $_GET['id'];
But cant figure out to do it PROPERLY using laravel.
This is my route:
Route::get('viewbuild', function()
{
return View::make('viewbuild');
});
And on my view I have done e.g.:
<?php
$build = Build::find(20);
?>
{{ $build->id }}
This correctly searches the builds table for a row with the id of 2 and then displays its id.
What I now want to do is pull the '20' value from the URL.
I have tried:
Route::get('/viewbuild/{build_id}', function($build_id = null)
{
$data = array(
'build_id' => $build_id,
);
return View::make('viewbuild', $data);
});
And then on my view:
$build = Build::find(build_id);
But I get undefined constant errors.
Any help on this?
Basically i can see two things from quick looking at your code:
A typo when setting the array to be passed to the view build_ud should be build_id i presume
You are referencing a constant for the build_id (no $ sign) in your view instead of the passed variable which is passed to the view. Ie:
$build = Build::find(build_id);
should be:
$build = Build::find($build_id);
Your route closure should look like this:
Route::get('/viewbuild/{build_id?}', function($build_id = null)
{
// Query the database here instead of inside the view
$build = Build::find($build_id);
return View::make('viewbuild', compact('build'));
});
I'm stuck trying to get joomla full article to render in a tab. The tab is working. I just canĀ“t render the article content. This is where I am now.
This is helper.php
public static function getArticle($articleId)
{
JModelLegacy::addIncludePath(JPATH_SITE.'/components/com_content/models', 'ContentModel');
$model = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article = $model->getItem((int) $articleId);
$fullarticle = $item->fulltext;
$itemsHtml = '<div>'. $fullarticle .'</div>';
return $itemsHtml;
}
And this is in default.php
...code...
else if ($list_of_tabs['use'][$i][0] == 'article'){
echo '<div class="tab-pane '.$active.'" id="'.$i.$rid.'">'.
modJpTabsHelper::getArticle($list_of_tabs['article'][$i], $params) .
'</div>';
}
...code...
If you need more info. Don't hesitate to ask.
What are you trying to achieve: to write your own Joomla! extension which displays articles in a tab or you just need to display your J! articles in a tab?
If it's a latter, then there are already some nice and free (as in a "free bear") add-ons written just for that.
You are trying to use the model part of an MVC as a thing to render.
You should use the MVC system - using a controller to gathering the model and the view, and then you can render the model with the attached view, via the controller.
So you use something like (I've not tested this - you will need to correct it).
$filter=array('id' => $i->query['id']);
$options=array('filter_fields' => $filter,'ignore_request' => true);
$ctl = new ContentModelController();
$view = $ctl->getView( 'Article');
$model = $ctl->getModel( 'Article','',$options);
you may need to set params from application, eg..
$model->setState('params', JApplication::getInstance('site')->getParams());
then continue
$view->setModel( $model, true );
$result = $view->display();
Make sure that you have JLoader::import'ed any classes/classpaths - j. tends to fail silently if they aren't found, which can be difficult to trace.
Sorry, it's only a partial solution - but hopefully it may put you on the right track.
Here was the problem:
$fullarticle = $item->fulltext;
Article object from model was in variable $article not $item:
$article = $model->getItem((int) $articleId);
So getting property fulltext from article object should be:
$fullarticle = $article->fulltext;
I have just started working with Mustache template engine. I am currently using PHP implementation of it (https://github.com/bobthecow/mustache.php/wiki). I am using helpers to manipulate the way data is rendered.
$data = array("name" => "abhilash");
$template = "Hello {{name}}, {{#bold}}Welcome{{/bold}}";
$m = new Mustache_Engine(array(
"helpers" => array(
"bold" => function($content) {
return "<b>$content</b>";
})));
$html = $m->render($template, $data);
With the help of this I am able to render 'Welcome' with bold font. I would like to know if it is possible to manipulate $data with the help of helper function. For example if the template is like below and I have a helper function registered as dataSource, I would like to use it to collect some data (say key-value pair) from datasource_func_name() and append it to $data.
{{#dataSource}}datasource_func_name{{/dataSource}}
Hi {{name}}
That's normally not how you would use helpers. However, Mustache basically expects a data souce, so why not inject it directly?
$html = $m->render($template, $dataSource);