Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions spec/marten/template/ext/hash_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,24 @@ describe Hash do
it "returns the expected result when requesting the 'values' attribute" do
({"a" => 1, "b" => 2, "c" => 3} of String => Int32).resolve_template_attribute("values").should eq [1, 2, 3]
end

it "returns the value for a hash key used as attribute" do
({"type" => "abonnement", "montant" => "60.00"} of String => String)
.resolve_template_attribute("type").should eq "abonnement"
end

it "returns the value for a hash key with integer values" do
({"count" => 42} of String => Int32).resolve_template_attribute("count").should eq 42
end

it "falls back to standard attributes when key does not exist" do
({"a" => 1} of String => Int32).resolve_template_attribute("size").should eq 1
end

it "raises UnknownVariable for non-existent key and non-existent attribute" do
expect_raises(Marten::Template::Errors::UnknownVariable) do
({"a" => 1} of String => Int32).resolve_template_attribute("xyz")
end
end
end
end
12 changes: 12 additions & 0 deletions src/marten/template/ext/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,16 @@ class Hash
include Marten::Template::CanDefineTemplateAttributes

template_attributes :any?, :compact, :empty?, :keys, :none?, :one?, :present?, :size, :values

# Allows to resolve hash keys as template attributes.
#
# This makes it possible to access hash values using `{{ my_hash.my_key }}` in templates,
# in addition to the standard hash methods (empty?, size, keys, etc.).
def resolve_template_attribute(key : ::String)
if has_key?(key)
self[key]
else
previous_def
end
end
end
Loading