I have this route:
_view_tag:
pattern: /topic/{tid}
defaults: {_controller: "MyCoreBundle:ViewTag:index" }
And I want to show url like this: example.com/topic/Web+development. I use href="topic/{{ topicname|url_encode() }}". It is works, but of course it is not proper way, so I change to href="{{ path('_view_tag', {'tid': topicname|url_encode() } ) }}". But it is not showing example.com/topic/Web+development, it shows example.com/topic/Web%2Bdevelopment.
I also try this:
{% set _tid = topicname|url_encode() %}
<a href="{{ path('_view_tag', {'tid': _tid } ) }}" ...
But still not working
My question is, how to make it show example.com/topic/Web+development using twig path function?
The path function takes care of url-encoding for you. Your problem is that your space got encoded twice: first to a +, then that got converted to %2b. This will work:
path('_view_tag', { 'tid': topicname } )
Related
I'm trying to render this Jinja2 template:
#app.get("/", response_class=HTMLResponse)
async def read_root(request: Request, item: Optional[str] = None):
item = "<script>"
return templates.TemplateResponse('index.html', {
'request': request,
'item': item
})
but when I use the variable in the HTML template, for example:
<h1>{{item}}</h1>
it shows this in the code:
<h1><script></h1>
is there anyway to decode that variable to show as it is declared?
FastAPI uses the templating support in starlette, which sets the Jinja2 autoescape option by default.
You can disable that like this:
templates = Jinja2Templates(directory="templates")
templates.env.autoescape = False
With more recent versions of starlette, you may also be able to do this:
templates = Jinja2Templates(directory="templates", autoescape=False)
...but with the version I'm running the latter option fails. The former option should work in any case.
Just found out how to do it,
adding in the HTML:
{% autoescape false %}
{{ your_variable }}
{% endautoescape %}
Another way is to wrap the markup you consider safe to render in markupsafe.Markup.
Overview:
I am working on a project that has dozens of .Liquid (Shopify) snippets with <script> tags inside of them containing JS code.
They're similar to HTML, they look something like this:
{% assign variable = 'test' %}
<p>hey {{variable}}</p>
<script>console.log("hey")</script>
{% schema %}
{
...json stuff
}
{% endschema %}
Issue:
Basically what I wanna do is get the content inside <script>, manipulate it and replace with the new manipulated one.
I managed to do this using cheerio, but it ends up messing up the Liquid variables since it doesn't recognize them.
My previous code was looking something like this:
let html = cheerio.load(code, { _useHtmlParser2: true });
const { data: js } = html("script").get()[0].children[0];
html("script").get()[0].children[0].data = await minifyJS(js);
const result = html.html();
Expected Behavior:
I need to:
Find all script tags in a HTML string;
Get the code inside of the <script> tag;
Manipulate this code (minify, essentially);
Replace it with the now minified code.
I am trying to avoid using regex, but I can't foresee any other solutions.
Any suggestion is greatly appreciated.
Thank you!
To get the content inside tags you can use Regular Expressions
<script(.|\n)*?<\/script>
This is just the regex
let str = <Whatever string or data you want to extract script tags>;
let result = let result = str.match(/<script(.|\n)*?<\/script>
/g);
console.log(result);
in result you will get the content inside the script tag
This question maybe kind of silly but I'm a newbie for symfony anyway.
prescenario I pass a variable from controller into index.html.twig by doing this
return $this->render('index/index.html.twig', [ 'department'=>$departments,'URILink'=>$URILink,'departmentDetail'=>$departmentDetails,'contentCell'=>$this->mContentCell ]);
After using {% dump %} it shows me
"department" => array:3 [▶]
"URILink" => "http://localhost/index/department/"
"departmentDetail" => array:1 [▶]
"contentCell" => "department.html.twig"
Then I need to reuse the variable contentCell as string in template to form syntax similar to this ;
<div>{{ include ('department.html.twig'),[departmentDetail:departmentDetail]</div>
For my first attempt I tried this,
<div> {{ include ({{ContentCell}}),[departmentDetail:departmentDetail]}} </div>
Unfortunately it showed me this error
A hash key must be a quoted string, a number, a name, or an expression
enclosed in parentheses (unexpected token "punctuation" of value "{".
Any idea how could I use the variable
contentCell as string value appropriately?
try this:
{% include contentCell with { departmentDetail : departmentDetail} %}
Answer here pass data to twig
You can include a template like this per:
{{ include('YourBundle:ControllerName:yourAction.html.twig', {'variableName': yourData}) }}
Or like this per http://twig.sensiolabs.org/doc/tags/include.html
{% include 'template.html' with {'foo': 'bar'} %}
after try'n try at last I found the the trick how to do it
i take similar analogy for
{{dump(var)}}
so attempt to do this
{{include (contentCell,{'departmentDetail' : departmentDetail}) }}
and it work like charm :) nice
I defined my route so:
$app->get('/about', function ($request, $response, $args) {
return $this->view->render($response, 'about.twig');
})->setName('about.page');
I'm interested to get route link by name like: {% get_route('about.page') %}
How can I achieve this?
In Slim3 there is the path_for(name) function. F.ex:
{{ path_for('about.page') }}
Reference: http://www.slimframework.com/docs/features/templates.html
The slim/twig-view component exposes a custom path_for() function to your Twig templates. You can use this function to generate complete URLs to any named route in your Slim application. The path_for() function accepts two arguments:
1 A route name
2 A hash of route placeholder names and replacement values
Note: The path_for uses the function of the router which is $router->pathFor(..)
Why not to use {%
{% is a control structur in twig, Message: Unknown "path_for" tag in "base.twig" at line XX. is displayed because there is no such tag as control structur defined so twig doesn't know that this is actually a function.
So use the output structur in twig {{.
Is this possible?
Yes.
IIRC
{{ path_for('about.page') }}
Reference:
https://github.com/slimphp/Twig-View/blob/master/src/TwigExtension.php#L37
EJS2 can only do character to be use with angle brackets for open/close:
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
I would like to use {{ }} instead of <% %>, previous version will allow this esj.open = '{{' and esj.close = '}}'.
Any help?
EJS has been updated & changed maintainers, so the main site is found here: https://ejs.co/
and the Github is here: https://github.com/mde/ejs
Unlike previous versions of EJS, you can't use completely custom delimiters now - you can use 'partial' custom delimiters - the first set of brackets aren't optional, but the following character is. To set up a custom delimiter you can do the following:
// app.js
const ejs = require('ejs');
ejs.delimiter = '?';
app.get('/', (req, res) => {
res.render('index', {
myVariable: 'Hey!'
});
});
// index.ejs
<div>
<p>
<?=myVariable ?>
</p>
</div>
// index.html (rendered output)
<div>
<p>
Hey!
</p>
</div>
You can add a complete options object and other things, but hopefully that gets you started if you want to change the default delimiters.
Documentation states that custom delimiters are supported:
https://github.com/tj/ejs#custom-delimiters
This isn't possible without modifying the module's source code.
My solution to using custom delimiters is be doing a string replace on the template
const template = fs.readFileSync(path.join(__dirname, './template.html'), 'utf8').replace('{{', '<%').replace('}}', '%>')
const render = ejs.compile(template)
This allows me to declare my template like this:
{{ if (someVar) { }}
{{= someVar }}
{{ } }}