Module: Phlex::Elements

Included in:
HTML, HTML::StandardElements, HTML::VoidElements, SVG::StandardElements
Defined in:
lib/phlex/elements.rb

Overview

Extending this module provides the #register_element macro for registering your own custom elements. It's already extended by HTML and SVG.

Examples:

module MyCustomElements
	extend Phlex::Elements

	register_element :trix_editor
end

class MyComponent < Phlex::HTML
	include MyCustomElements

	def template
		trix_editor
	end
end

Instance Method Summary collapse

Instance Method Details

#register_element(method_name, tag: nil) ⇒ Symbol

Note:

The methods defined by this macro depend on other methods from SGML so they should always be mixed into an HTML or SVG component.

Register a custom element. This macro defines an element method for the current class and descendents only. There is no global element registry.

Examples:

Register the custom element <trix-editor>

register_element :trix_editor

Parameters:

  • method_name (Symbol)
  • tag (String) (defaults to: nil)

    the name of the tag, otherwise this will be the method name with underscores replaced with dashes.

Returns:

  • (Symbol)

    the name of the method created



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/phlex/elements.rb', line 35

def register_element(method_name, tag: nil)
	tag ||= method_name.name.tr("_", "-")

	class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
		# frozen_string_literal: true

		def #{method_name}(**attributes, &block)
			target = @_context.target

			if attributes.length > 0 # with attributes
				if block # with content block
					target << "<#{tag}" << (Phlex::ATTRIBUTE_CACHE[respond_to?(:process_attributes) ? (attributes.hash + self.class.hash) : attributes.hash] || __attributes__(**attributes)) << ">"
					yield_content(&block)
					target << "</#{tag}>"
				else # without content block
					target << "<#{tag}" << (Phlex::ATTRIBUTE_CACHE[respond_to?(:process_attributes) ? (attributes.hash + self.class.hash) : attributes.hash] || __attributes__(**attributes)) << "></#{tag}>"
				end
			else # without attributes
				if block # with content block
					target << "<#{tag}>"
					yield_content(&block)
					target << "</#{tag}>"
				else # without content block
					target << "<#{tag}></#{tag}>"
				end
			end

			#{'flush' if tag == 'head'}

			nil
		end

		alias_method :_#{method_name}, :#{method_name}
	RUBY

	registered_elements[method_name] = tag

	method_name
end