Support Forum
Hi,
Somehow I can't figure out how to pass data from Twig to PHP code.
I'm calling a view like this in a FacetWP listing:
[mbv name="display-related-things" vw_postid={{post:id}}]
Inside the view, I can display the post ID like this:
Post ID is {{ vw_postid }}.
But how do I pass that post ID to PHP code in the view, so I can do a query with it?
This does not work:
{% set foo = {{ vw_postid }} %}
Hi,
You can just use the variable vw_postid
without the pair of curly brackets (which means output value)
{% set foo = vw_postid %}
Post ID is {{ foo }}
To learn more how to use Twig code, please follow this link https://twig.symfony.com/doc/3.x/templates.html#ides-integration
Hi Long,
I guess that works, but somehow the value is not what I expect. Here's an example:
{% set listing_current_post_type = vw_posttype %}
Type is {{listing_current_post_type}}
{% if (listing_current_post_type == 'activity') %}
Match
{% else %}
Nomatch
{% endif %}
The output of the view is:
Type is activity Nomatch
I'd expect a match.
I have a similar issue with the post ID (integer) I want to use. Somehow it's not recognized as an integer.
Hi.
It might be a typo issue on your testing code. The code works as well on my site, screen record https://imgur.com/a/3VxLe0l
Hi Long,
Your findings made me do a different test. I forgot the quotes around the variable in the view, but that does not make a difference. I now have this in the FacetWP listing, but it does not work:
[mbv name="display-related-things" vw_posttype="{{post:type}}"]
Passing the hardcoded value does work:
[mbv name="display-related-things" vw_posttype="activity"]
Somehow the value passed by FacetWP does contain the string "activity", but it fails to match in the if-statement. The hardcoded string works fine. Really weird.
I asked FacetWP as well but they don't know. Do I need to format the received value somehow before I can use it in a view?
Hi,
I think when outputting the view content, the variable post type is rendered also. But when assigning to a variable, it is just the string {{post:type}}
and does not match in the if statement. If it is too complicated in this case, please use the hardcoded post type string.
Hi Long,
I just tried this:
{% set listing_current_post_type = vw_posttype %}
Type is {{listing_current_post_type}}, length is {{listing_current_post_type|length}}
The output is this:
Type is activity, length is 13
It should be 8 characters, but it counts 13. That's the problem.
I can't use the hardcoded string, the values are dynamic.
I can give you access to the site if it's not possible to solve this here.
It looks like the dynamic tags that are used to pass data to the view are parse after the shortcode is parsed.
[mbv name="display-related-things" vw_postid={{post:id}}]
I'm not sure yet. Will look into it and update here.