ujwal dhakal
ujwal dhakal

Reputation: 2469

Passing variables to YML file from PHP while parsing YML

Here is my YML file:

edit: '0'
parent: '0'
seo_title: 'gallery |'
seo_description: ''
seo_keywords: ''
fbtab: '0'
status: '1'
exceptions: {% pageType %}
calltoaction: 0

in PHP file:

$pageType = "something";
dump(Yaml::parse(file_get_contents('pathToYmlFile')));

Problem is passing $pageType to YML file

Upvotes: 2

Views: 2150

Answers (2)

Kirill Rogovoy
Kirill Rogovoy

Reputation: 591

You don't actually need this.

Remember, you convert a YAML-file into a PHP structure.

After you parsed it, you can do whatever you want with that structure. So, you can assign the value you want to the appropriate field.

Pseudo-code:

$pageType = "something";
$parsed = Yaml::parse(file_get_contents('pathToYmlFile'));
$parsed->exceptions = $pageType;

You didn't specify your particular use-case, but, as far as I see from your code sample, it fits.

Upvotes: 2

flyx
flyx

Reputation: 39768

YAML is not a templating language. It has no knowledge about variables or replacement. You have two options:

  • Use a templating language to preprocess your YAML file before parsing it. This is done for example in SaltStack with YAML and Jinja.
  • Make the replacements inside the loaded strings after parsing. This makes only sense for some specific use-cases, like when some YAML value always will be replaced by a variable value, but multiple different variables can be chosen inside the YAML for replacement.

A third option would be to use YAML tags to denote that the value you give is a variable name. Example:

exceptions: !var pageType

!var here defines an explicit tag for the following scalar pageType. Most YAML implementations would allow you to register a custom constructor for a !var tagged scalar – Unfortunately, Symphony's YAML component is not equipped to do such things, so this is not an option you can go for.

Upvotes: 2

Related Questions