I'm working on a Silverstripe 4 project where we need to include a SS template file from a path.
Here's a simple example giving the gist of what I'm trying to achieve.
class ExampleController extends ContentController
{
public function IncludeTemplateFromFilePath() {
var $FilePath = '/path/to/file';
???
return $output
}
}
Template syntax:
<div>$IncludeTemplateFromFilePath</div>
I've had a look through the SSViewer documentation and looked at the Silverstripe source code but can't work out the correct syntax to make this work.
There are many examples of:
return SSViewer::get_templates_by_class(static::class, $suffix, self::class);
But what is the syntax to get a template from it's filepath?
I believe you can do the following:
public function IncludeTemplateFromFilePath()
{
return SSViewer::execute_string(
file_get_contents('/path/to/Template.ss'),
[
'Content' => 'Value that will be in $Content when used in /path/to/Template.ss'
]
);
}
Reference: http://api.silverstripe.org/4/SilverStripe/View/SSViewer.html#method_execute_string
Related
I am working on Symfony application and using Twig for layout.
I facing wrong output issue i google it but can't find the solution.
I have date & time 201801031400 I used this
{{ val.start_date|date("m/d/Y") }}
but get the wrong output 10/27/8364
When i used this {{ "now"|date("m/d/Y") }} it give me correct output
Thanks in Advance!
You need to a function to Twig to achieve this, you can see how to register an extension here
TwigExtension
namespace My/Project/Twig/Extensions
class ProjectTwigExtension extends Twig_Extension {
public function getFunctions() {
return array(
new Twig_SimpleFunction('convert_api_date', function($date) {
return new DateTime($date);
}),
);
}
public function getName() {
return 'ProjectTwigExtension'; //this is mandatory
}
}
twig
{{ convert_api_date('201801031400') | date('d/m/Y') }}
{{ convert_api_date('201801031400') | date('H:i') }}
Above answer will perfectly alright i just my solution code too.
First Twig date filter not support the 201801031400. so for this you have to make your own extension.
How to create twig extension create twig extention
<?php
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
class DateParserFilter extends \Twig_Extension
{
public function getFilters ()
{
return array(
new \Twig_SimpleFilter('parse_date', array($this, 'parseDate'))
);
}
public function parseDate ($string, $formats)
{
if (is_string($formats))
{
$formats = array($formats);
}
foreach ($formats as $format)
{
$dateTime = \DateTime::createFromFormat($format, $string);
if ($dateTime !== false)
{
return $dateTime;
}
}
return $string;
}
public function getName ()
{
return "parse_date";
}
}
after this use your own extension filter first then use twig builtin date filter example show below :)
{{ val.start_date | parse_date(["YmdHi", "d/m/Y H:i"]) | date("M d, Y") }}
Its depend what you have in my case i have [2018][01][03][14][00] = [Y][m][d][H][i]
hope it will help you :)
source of this extension - link
You have to divide your unix timestamp value by 1000.
I'm still not sure with what it's related, but this operation is used by authoritative online converters, that most likely faced the same problem.
I came to this conclusion thanks to this answer Converting a UNIX Timestamp to Formatted Date String.
Below is the proof that your unix timestamp is correct:
1) from www.freeformatter.com
2) from www.epochconverter.com
The data is slightly different due to the time zone. It must be taken into account.
Write in the comments, why should I divide by 1000. I myself will be interested.
I'm using unclecheese/dashboard module i use it like it is described in the README. I use silverstripe 3.5.3
I get this error message:
[User Warning] None of the following templates could be found (no
theme in use): DashboardMostActiveUsersPanel.ss
this is the panel content:
class DashboardMostActiveUsersPanel extends DashboardPanel{
private static $db = array (
'Count' => 'Int',
);
public function getLabel() {
return 'Most Active Users';
}
public function getDescription() {
return 'Shows the most active Users.';
}
public function getConfiguration() {
$fields = parent::getConfiguration();
$fields->push(TextField::create("Count", "Number of users to show"));
return $fields;
}
public function getMostActiveMembers() {
$members = Member::get()->sort("Activity DESC")->limit($this->Count);
return $members;
}
public function PanelHolder() {
return parent::PanelHolder();
}
}
this is the template:
<div class="dashboard-recent-orders">
<ul>
<% loop $MostActiveMembers %>
<li>$Name, $Activity</li>
<% end_loop %>
</ul>
</div>
This is where the error comes from: theme_enabled is empty
Config::inst()->get('SSViewer', 'theme_enabled‘)
I set the theme in the CMS Backend and i set it in config.yml like
SSViewer:
theme: 'my-theme'
I also tried to put the templates in different folders in /themes directory. But still no luck. What am i missing any help would be highly appreciated.
Themes only affect the frontend. The backend does not use them. You'll need to put the template in your mysite/ directory, or whatever your $project is.
I am looking to use substr_count in Twig, does anything exist already? I want to perform something like this;
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
I can do an extension but it seems this might be something built in already that I have missed.
How about this?
{%set count = text|split('is')|length-1 %}
This doesn't exist in the list of Twig functions or filters.
You'll have to write your own custom function/filter or try a package (note; I've never used this package so can't comment on it, but was on the first page of Google results).
I went for an extension
namespace AppBundle\Twig;
class SubStrCountExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('substr_count', array($this, 'substr_count')),
);
}
public function getName()
{
return 'substr_count_extension';
}
public function substr_count($str, $char)
{
return substr_count($str, $char);
}
}
And in services.yml
app.twig_extension.substr_count_extension:
class: AppBundle\Twig\SubStrCountExtension
tags:
- { name: twig.extension }
I use solution in Symfony 3.2.8 but in the description does not say this block of code should is inside : services
If you does not make show this error:
There is no extension able to load the configuration for .....
This code should is inside services this is correct:
services:
app.twig_extension.substr_count_extension:
class: AppBundle\Twig\SubStrCountExtension
tags:
- { name: twig.extension }
Finally, the correct use in twig is:
tu placa es: {{substr_count(datos.picoyplaca,4)}}
Regards
So I have created my custom view helper and used it in layout.phtml like this:
<?php echo $this->applicationBar(); ?>
It is working flawlessly in the browser but my unit tests that were working before are failing now:
1) UnitTests\Application\Controller\IndexControllerTest::testIndexActionCanBeAccessed
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for applicationBar
When I comment out the view helper in the layout file, test passes again.
I have the same problem, and i solved it in not a good way (but it solved for my specific problem).
The phpunit tests is not finding my factories view helpers, but it is finding my invokables. Then, i did the following:
public function getViewHelperConfig() {
return array(
'factories' => array(
'aplicationBar' => function($service) {
$applicationBar = new ApplicationBar();
return $applicationBar;
},
),
'invokables' => array(
'applicationBar' => 'Application\View\Helper\ApplicationBar',
),
);
When i use the browser, it uses the correct Factory. When i use phpunit, it uses the invokables.
The problem happens when i need to set some parameters. And then, i set some default parameters, that will be used only by phpunit.
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class ApplicationBar extends AbstractHelper {
protected $parameter;
public function __construct($parameter = 'something') {
$this->parameter = $parameter;
}
public function __invoke() {
return $this->parameter;
}
}
It is not the best solution, but if i solve it in a better way, i will post here.
We can create a view from admin panel. But I want to create a view using php code. Can anyone show me the way?
There is code floating around that wouldn't work for me. But This one did. Add this php to your .module file. Then create a views folder and then put all your views in there with the extension of .inc. Each view file will simply be <?php followed by the exact export of the view...
/**
* Implements hook_views_api().
*/
function MODULENAME_views_api() {
return array ('api' => 3.0);
}
function MODULENAME_views_default_views() {
// Check for all view file in views directory
$files = file_scan_directory(drupal_get_path('module', 'MODULENAME') . '/views', '/.*\.inc$/');
// Add view to list of views
foreach ($files as $filepath => $file) {
require $filepath;
if (isset($view)) {
$views[$view->name] = $view;
}
}
// At the end, return array of default views.
return $views;
}