Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse a block of code in YAML

Tags:

yaml

I want to reuse a hash in YAML:

Defaults: &defaults   Company: Foo   Item: 123  Computer: *defaults   Price: 3000 

However, this generates an error.

Is the only way to anchor each field value separately like this?

Defaults:   Company: &company Foo   Item: &item 123  Computer:   Company: *company   Item: *item   Price: 3000 
like image 781
ajsie Avatar asked Dec 11 '11 18:12

ajsie


People also ask

What is << In YAML?

The “<<” merge key is used to indicate that all the keys of one or more specified maps should be inserted into the current map. If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the current mapping, unless the key already exists in it.

Does YAML support multiline comment?

YAML does not support block or multi-line comments.

Can we define a variable in YAML file?

YAML does not natively support variable placeholders. Anchors and Aliases almost provide the desired functionality, but these do not work as variable placeholders that can be inserted into arbitrary regions throughout the YAML text. They must be placed as separate YAML nodes.


2 Answers

Try reusing a full group by importing it:

Defaults: &defaults   Company: foo   Item: 123  Computer:   <<: *defaults   Price: 3000 

Documentation: http://yaml.org/type/merge.html

like image 58
Gabriel Oliveira Avatar answered Oct 14 '22 16:10

Gabriel Oliveira


# sequencer protocols for Laser eye surgery --- - step:  &id001                  # defines anchor label &id001     instrument:      Lasik 2000     pulseEnergy:     5.4     pulseDuration:   12     repetition:      1000     spotSize:        1mm  - step: &id002     instrument:      Lasik 2000     pulseEnergy:     5.0     pulseDuration:   10     repetition:      500     spotSize:        2mm  - step: *id001                   # refers to the first step (with anchor &id001) - step: *id002                   # refers to the second step - step: *id001 - step: *id002 

sample from wikipedia

like image 21
zed_0xff Avatar answered Oct 14 '22 15:10

zed_0xff