Chapter 4. Blocks and Layout Containers
The line-wrapping tool in Chapter 3 has only one action in its UI: fill in three boxes, click once, and see three results. You can build this kind of UI with Interface in a few lines, because it has only one column of inputs and one column of outputs.
The workbench is different. It needs a title, an area that collects inputs, an area that holds results, and later tables, files, and chat. These areas exist at the same time; they are not sequential. Interface cannot express this — its layout is fixed: inputs on the left, outputs on the right, the button in the middle.
Blocks can. With it, you no longer describe “how a function becomes a UI”; you describe “what a page looks like”. Which areas are on the page, which components are in each area, and what sits inside what.
This chapter builds the single-page skeleton of the workbench. When it’s done, the page is divided into three areas with a clear structure, but the buttons don’t respond yet. Events are a topic for Chapter 5. This chapter’s UI is static.
4.1 From a Single Operation to Multiple Interaction Areas
Interface’s model is “one operation”. It assumes the user opens the page, fills in a few values, clicks a button, sees a few results, and closes it. The app in Chapter 2 and the line-wrapping tool in Chapter 3 both fit this model. One operation, one result, inputs and outputs each taking one column — Interface’s fixed layout lines up exactly.
The workbench doesn’t fit. It is “several things on one page”. Text cleanup is one, table checking is another, file handling is a third. Users come in looking for entry points to work, not to perform one particular operation. Interface can’t hold this kind of UI.
First, the areas are side by side. The title belongs neither to inputs nor to outputs; the result area takes no parameters, it only displays things. Interface cuts the page into two piles, “inputs” and “outputs”, with no place to put something that “belongs to neither pile”.
Second, the areas have a containment relationship. The Body, Statistics, and Notice in the result area form one group and should be drawn inside one frame; the three fields in the input area are another group. In Interface all inputs are laid out flat in a single column, so you can’t separate groups.
Third, the areas keep growing. Chapter 5 adds buttons to the input area, Chapter 9 adds a table, Chapter 13 adds a chat. Every addition has to find a spot outside those two columns, and Interface has no third spot.
Blocks’s model is “one page”. You write the nesting relationship between containers and components; what the page looks like depends on how you nest them. It doesn’t presuppose how many areas the page has, or who is on the left.
The skeleton this chapter builds looks like this.
- A top strip: a title and one line of description;
- A middle block: inputs on the left (source text, characters per line, keep edits, plus a button), results on the right (body, statistics, notice);
- A bottom block: advanced options, hidden by default.
Three areas, two directions, one corner that doesn’t appear by default. Together, these use every container this chapter covers.
Why spend a whole chapter just placing the skeleton? Because every later chapter adds to this skeleton. Chapter 5 adds events, Chapters 6 to 13 each add a module, and Chapter 18 splits it into multiple pages. Place the skeleton wrong and every later chapter has to be reworked; place it right and adding a module is just “writing a few more lines inside some using”.
The sample is in samples-en/chapter04, with two projects. core holds the line-wrapping and statistics rules and does not reference Gradio.NET; Chapter04.csproj only handles the page. At the skeleton stage there are no events yet, so the result area first gets a sample computed at startup. Run core once and fill in the result. That way the page isn’t empty, and you can see how much space each area takes and whether things get cramped with a lot of text. This sample is replaced by real results only when Chapter 5 wires up the buttons.
After you launch it, you’ll find the “Clean up” button does nothing when clicked. That’s this chapter’s state, not a defect. The first thing Chapter 5 does is bind an event to it.
This chapter’s scope is clearly drawn too. Event binding is left to Chapter 5; the collapsing and paging containers like Tabs, Accordion, and Sidebar are left to Chapter 18; themes and CSS are left to Chapter 19. This chapter uses only four containers, to lay the page out into something usable.
4.2 Blocks and the Component Build Context
First, look at how this page is put together.
var demo = gr.Blocks(title: "Personal Local Workbench");
using (demo)
{
// Title area: only a title and one line of description, taking up a full row.
using (gr.Column())
{
gr.Markdown("# Personal Local Workbench");
gr.Markdown("A piece of text, a table, and a few files are all handled on this one page.");
}
// Main area: inputs on the left, results on the right.
using (gr.Row())
{
using (gr.Column(scale: 2, minWidth: 480))
{
gr.Markdown("### Text Cleanup");
gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
gr.Checkbox(label: "Keep my edited body", value: false);
gr.Button("Clean up", variant: "primary");
}
using (gr.Column(scale: 1, minWidth: 320))
{
using (gr.Group())
{
gr.Markdown("### Result");
gr.Textbox(label: "Body", lines: 12, value: preview.Text, interactive: true);
gr.Textbox(label: "Statistics", lines: 2, value: Stats(preview.Report), interactive: false);
gr.Textbox(label: "Notice", lines: 2, value: Notice(preview.Report), interactive: false);
}
}
}
// Advanced area: hidden by default, invisible on the page, and leaves no empty space.
using (gr.Row(visible: false))
{
gr.Markdown("### Advanced options");
gr.Textbox(label: "Separator", value: ",", info: "What separates multiple values");
gr.Number(label: "Line limit", value: 200);
}
}
demo.Launch();
This code rests on one premise that runs through the whole chapter. A component belongs to the innermost open container.
Look at the first line. The title in gr.Blocks(title: "Personal Local Workbench") is the name on the browser tab and the value of the title field in /config. It has nothing to do with the # Personal Local Workbench on the page. The latter is a Markdown component — it shows whatever you write — and the two can differ.
gr.Blocks(...) creates the root container. using (demo) opens it, and everything inside the braces is placed on the root. using (gr.Row()) opens another layer inside, so components in that layer land on the Row. Go further in with using (gr.Column(...)) and components land on the Column. When a brace ends, that layer closes and later components go back to the previous layer.
Figure 4-1 Components land in the innermost open container
Figure 4-1 shows three moments. Just after entering Blocks, the top of the stack is the root, so components land directly on the root. After entering Row, the top is the Row, so components land in the Row. Enter Column and the top is the Column, so components land in the Column. That’s why gr.Markdown("### Text Cleanup") appears in the input area — it’s written inside that Column’s braces.
There’s an easy-to-miss detail here. A container is pushed onto the stack as soon as it’s created; using only pops it off when the braces end. So if you “don’t write using”, that layer stays open.
using (demo)
{
var input = gr.Column(); // pushed onto the stack, no matching pop
gr.Textbox(label: "Source text"); // lands in Column
gr.Textbox(label: "Statistics"); // also lands in Column
gr.Button("Clean up"); // still lands in Column
}
All three components above are in the input column; none went back to the root. To verify, create another Row after the Column and you’ll find the Row has also become a child of the Column, because the top of the stack is still the Column. This mistake throws no error — the page still renders — only everything is crammed into the same area.
Containers must close in nesting order: using the outer layer first, then the inner, and in reverse when exiting. Closing in reverse (outer first, then inner) doesn’t throw an exception, but later components land in a container you didn’t intend. This kind of problem is hard to spot by reading the code; on the page the component positions are simply misplaced.
There’s a third way of writing it, harder to track down than the two above.
var outside = gr.Textbox(label: "Created first"); // written before using (demo)
No error, no warning, and the box isn’t on the page. Its Parent is null and its Id is -1, meaning “it was never added to any page”. The component object is still a valid object; nobody just holds it. So for the question “I clearly wrote this textbox, why isn’t it on the page?”, the first thing to check is which layer of braces it was written in.
The three ways of getting the position wrong have different symptoms and different ways to find them.
| Way of writing | Error? | Symptom | How to find it |
|---|---|---|---|
Container without using | No | All later components crammed into one area | Look at the page, one area is missing |
Component outside all using blocks | No | The component is not on the page | Id is -1, Parent is null |
| Braces out of order | No | Components land in an adjacent area | Look at the layout tree in /config |
The /config mentioned in the third row is another way to check. After launching the sample, open http://127.0.0.1:7860/config; it has a layout field, which is the container tree for the whole page. The indentation in your code should correspond one-to-one with this tree: indent one level more in the code and the tree gains a level. If they don’t match, the braces are wrong. The later sections on containers keep coming back to this tree. It’s more precise than the page: the page only tells you “it looks off”, the tree tells you “where it’s off”.
Sealing
The page can’t be changed forever. Blocks has a “sealed” state; once sealed, adding components to it is rejected.
System.InvalidOperationException: This application is already being served, so it no longer
accepts blocks: the page a browser sees is the one written before the host started. Write the
UI before starting the host — the host seals the application when the first request arrives.
This error means the application is already being served, and the page is the one written before the host started; the UI must be finished before starting the host, and the host seals the application when the first request arrives.
When do you run into it? The most direct case: you call demo.Seal() before the page code is finished, then add components. The exception is thrown right there. The second is more common: putting demo.Launch() in the middle of the page code. Normally the process just stops there, the code after it never runs, and you see no error at all — only none of those components appear.
The timing of Seal is this: after Launch but before the page is visited, IsSealed is False; after the browser opens it once, it becomes True. So the exact order is, finish the UI first, then Launch. This has no exceptions and no need for a workaround. The point of Seal is to stop someone from changing the structure after the page has already been sent out.
One more thing: in everyday app writing you don’t need to call Seal manually. It’s used by the framework itself, and it’s what enforces “the UI must be finished before Launch”.
4.3 The Division of Labor Among Row, Column, and Group
Four containers, each with its own job.
| Container | Direction | What it manages | Typical use |
|---|---|---|---|
Row | Horizontal | Places children side by side, splitting width by scale | Inputs left, results right; a row of buttons |
Column | Vertical | Stacks children top to bottom, each its own block | Vertical arrangement inside one area |
Group | Vertical | Joins children into one block sharing an outer frame | A group of results, a group of related fields |
Form | Vertical | Generated automatically by the framework, wrapping consecutive form components | Don’t write it, see 4.4 |
Row and Column are layout directions; Group is “visually one whole”. The difference among the three is visible on the page.
In a Column each child is its own block, with a 16-pixel gap between blocks; in a Group the children share one outer frame with nothing separating them. This chapter’s result area uses Group. The Body, Statistics, and Notice boxes sit together and look like one “result panel” rather than three unrelated things. The input area uses Column. The three fields each take a row and are separated, because they were never one whole.
Figure 4-2 The skeleton’s structure tree, containers nested in containers, dashed boxes added by the framework
Figure 4-2 is the skeleton’s actual structure, read from the layout in /config and drawn as a tree. It’s simple to read: indentation means containment, blue is a layout node, black is a component, and the orange dashed boxes are groupings the framework added (covered in 4.4).
Look at a few positions.
- The topmost
columnholds the title and one line of description; it isn’t side by side with anything; - Under the
roware the two main columns: thescale=2column holds the inputs, thescale=1column holds the results; - In the result column there’s first a
group, and inside thegroupare the title and three output boxes; - The last
rowis markedvisible=false— the advanced area hidden by default.
There’s no limit on nesting depth. You can put a Column in a Row and a Row in that Column, as long as every layer opens a using. But as the layers grow, the code’s indentation is the first to suffer. This chapter’s skeleton goes at most four levels deep (Row → Column → Group → component); deeper than that and you should think about splitting it.
How to split? Write “one area” as a method and call it inside the using.
using (demo)
{
Header();
TextModule();
ResultPanel();
Advanced();
}
void TextModule()
{
using (gr.Column(scale: 2, minWidth: 480))
{
gr.Markdown("### Text Cleanup");
gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
gr.Checkbox(label: "Keep my edited body", value: false);
gr.Button("Clean up", variant: "primary");
}
}
Written this way, the indentation is always only two levels, and each area can be read and changed on its own. Mechanically nothing changes. The methods are called inside using (demo), and when called the root container is open, so the components built in the methods still land on the root. This chapter’s sample doesn’t split things up, because the whole point here is to see the nesting clearly.
A Row can hold more than three areas, with scale dividing by shares. Three columns at 3:2:1 with an available width of 1200 come out to 600, 400, 200. The more shares, the harder the ratio is to read — three columns is the practical limit; four or more usually means this screen is crammed with too much and you should consider splitting it with Tabs (Chapter 18).
You can also put a Row inside a Row. The most common use is “a row of buttons”. In a Column, the fields are on top and using (gr.Row()) holds two buttons side by side below. Here the buttons’ Row has no scale — it only handles horizontal placement and doesn’t take part in the outer width split; that’s the Column’s job.
How to choose between Group and Column? Look at whether this group of things “is one thing”. The three boxes in the result area are three facets of one thing, so use Group; the three fields in the input area are three different things, so use Column. There’s also a practical difference. Group removes internal gaps, so if you put fields that each need their own label inside, the labels end up very close together and cramped to read. Group is better for outputs, or for a set of short fields of the same kind.
Group differs from Row and Column in another way: it has no scale or minWidth parameters. That is, Group doesn’t take part in width splitting itself — how much it occupies is decided by the layer outside it; a Group placed in a Row is treated as one whole and gets one share. To make the result area take more width on a wide screen, you change the scale of the Column outside it, not the Group’s.
You can also put a Column or Row inside a Group. For example, if you want Body on the left and Statistics on the right in the result area, nest a Row with two Columns inside the Group. There’s no limit on combining containers; there’s only one criterion. Should this layer’s children sit side by side or stack up? Should they each be their own block or join into one block?
Launch the sample and the UI looks like this.
Figure 4-3 The skeleton’s initial UI: title area, input area, result area
Three areas, top to bottom. The title area fills a row; the main body is wide on the left and narrow on the right (2:1). The three fields in the input area each take a row with gaps between them; the three boxes in the result area sit together sharing one outer frame. That’s the difference between Column and Group — you can recognize it without looking at the code.
There’s one detail in the result area. “Body” has a white background and can be clicked into and edited; “Statistics” and “Notice” can’t. The interactive parameter decides this — more in 4.6.
4.4 Form and Automatic Grouping
In the table in the previous section, the Form row’s usage says “don’t write it”. But /config really does have form nodes — those are the three dashed boxes in Figure 4-2. Where do they come from?
At the end of rendering, the framework does one thing: it wraps consecutive form components into a form node. Form components are those that have a “value” and can be submitted — Textbox, Number, Checkbox, Dropdown, Slider, and so on. This chapter’s input area writes three of them.
gr.Markdown("### Text Cleanup");
gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
gr.Checkbox(label: "Keep my edited body", value: false);
gr.Button("Clean up", variant: "primary");
The three fields land in the same form, while Markdown and Button land outside it. You can see this wrapping directly in the layout of /config; the structure looks like this.
{"id": 15, "children": [{"id": 11}, {"id": 12}, {"id": 13}]}
15 is the automatically generated form; 11, 12, 13 are source text, characters per line, and keep edits. You didn’t write a single form in your code, yet it appears in the config.
When is the grouping broken? It breaks at a non-form component. Slip a line of description between two of those three fields in the input area and you get two forms instead of one; the same goes for Button — it doesn’t take part in grouping, so the “Clean up” button in the sample is outside the form. That’s the grouping rule: only form components go into a form.
This rule is also the only lever you have over grouping. To keep one group of fields separate from another, insert a Markdown between them. A small heading or a separating note both work; it becomes the break between the two groups. Conversely, to merge several items into one group, don’t put any non-form component between them — not even a single line of description.
Grouping doesn’t distinguish inputs from outputs. The three boxes in the result area (Body, Statistics, Notice) are also form components, so another form is generated inside the group. Even though “Statistics” and “Notice” are read-only and never meant to be filled in, this rule looks only at component type, not at what it does in this UI. Know this and you won’t be surprised by unexpected dashed boxes in the structure tree.
Grouping also affects width, and this is easier to get wrong than the grouping itself.
The form itself has no width; it’s the sum of the widths of the components it wraps. Each component counts as one share by default with minWidth 160, so a form with two fields carries scale 2 and minWidth 320. In a Column this has no effect — the column is vertical, width is set by the column, and the form gets scale 0, minWidth 0. But in a Row, the form does take part in the horizontal split.
The advanced area has exactly this structure: a Row with a Markdown heading and two fields. Right now it’s visible: false, so you can’t see it. Change that false to true, rebuild, and you’ll see a result that defies intuition. The heading isn’t on top; it sits side by side with the two fields, the heading taking 1 share and the fields 2 — at a 1280 viewport the heading is 400 wide and the fields 801.
The reason is the one above: Markdown itself takes 1 share, and the auto-generated form carries the two fields’ 2 shares. To get the heading on top, the correct way is to put the heading outside the Row, or wrap the two fields in a Column and put that into the Row.
So when you see oddities like “the heading went off to the side”, first count who at that level carries a scale. The auto-generated form is the one most easily forgotten — it isn’t in your code.
At this point one thing needs to be made clear, because it’s the most misunderstood point in this chapter. This form is not an HTML <form>.
There is no form tag on the page. In the browser that node is an ordinary div, just named form. So:
- Pressing Enter in a field does nothing — no submit, no refresh, no button triggered;
- To make a group of fields “submit together”, you rely on an event listing them all in
inputs. That’s Chapter 5’s content; formonly decides where these items are drawn, how wide they are, and whether there are gaps between them.
The framework only handles automatic grouping; submission still requires you to write an event. These two things are often bundled together in other frameworks, but here they’re separate. UI structure belongs to containers, behavior belongs to events, each minding its own business.
4.5 scale, minWidth, and Area Ratios
The two main columns have different widths. Inputs go on the left, results on the right, and the inputs need more width. Two parameters decide this.
using (gr.Column(scale: 2, minWidth: 480))
scale is “how many shares”, not pixels. Left 2, right 1 means the available width is split into three shares and the left takes two. At a 1280 viewport, the page content is 1216 wide, 16 pixels are left between the two columns, and the remaining 1200 splits into three shares of 400 each — so 800 on the left, 400 on the right. The numbers line up; that’s all scale means.
The title area has only two lines of text and fits in one column, so there’s no ratio to divide. Whether to split into columns depends on the content. If you also want a row of action buttons to the right of the title, write a Row with two columns and set the ratio as needed. Splitting isn’t mandatory — one more container means one more level of indentation, and on narrow screens one more line wrap to think about.
Treating scale as pixels is the most common mistake in this section. Write scale: 800 thinking “I want 800 pixels wide”, and this column and the neighboring scale: 1 column become 800:1 — the neighbor is squeezed into a thin line. scale only understands shares, and only has meaning when compared within the same level and the same Row; comparing across levels is meaningless, because each level splits its own width.
minWidth is a different matter. Below this width, stop placing side by side and wrap. The left requires at least 480, the right at least 320; the two add up to 800, plus the 16-pixel gap makes 816. When the available width is less than 816, the two columns stack into one.
Figure 4-4 Viewport narrowed to 700 pixels, the two main columns stack into one
Figure 4-4 is the same page with the viewport narrowed to 700 pixels. The page content width becomes 576, and the two main columns stack vertically. Inputs on top, results below — the order is the order you wrote. The title area has nothing to change; it only ever had one column.
What this figure shows is that scale and minWidth are not the same thing; they govern two directions. scale governs “how to split when wide”, minWidth governs “when to stop placing side by side when narrow”. Write only scale and no minWidth and things get cramped on narrow screens; write only minWidth and no scale and the two columns are always equally wide on wide screens.
First, tell the defaults apart. A Column’s scale defaults to 1 and minWidth to 320, so two columns with no parameters are 1:1 and only stack below 656; a Row’s scale defaults to “not given” — in a Row it’s the columns, not the row, that split the width. Components also have scale and minWidth (default 160), used when several components sit side by side in the same row; you’ll meet those in Chapter 6 on input components.
How do you set these two numbers? Three rules of thumb.
Use integer ratios for scale, not things like 1.37. A ratio is meant to be read by people: in 2:1 the first block takes two shares, so who should be wider needs no figuring out; 1.37:1 only makes the next person to change it guess what you were thinking.
Set minWidth by “how narrow this area can get and still be usable”, not by copying pixels from a design mockup. The input area has to fit an 8-line textbox, so 480 is a reasonable lower bound; the result area only holds short text, so 320 is enough. The problem with copying a mockup is that a mockup has one width, while users’ windows have countless.
A ratio isn’t a “fixed width”. It only decides how surplus space is split, not the minimum usable width. Drag the window from 1280 to 1920 and the two columns are still 2:1, but both get wider; narrow the window from 1280 to 900, the page content width drops to 704, and the two columns have already stacked — because 704 is less than 816. Both behaviors are automatic; you don’t write media queries or prepare a set of sizes for every breakpoint.
One more easily overlooked thing. After stacking, both columns become full-row width. That is, on narrow screens there’s no such thing as a “ratio” — only who comes first matters. So when you write a Row, think about it as you go. If these two blocks stack vertically, is the order still sensible? Put results above inputs and on narrow screens the user sees a bunch of empty boxes first.
4.6 The Effect of visible and interactive on the UI
The last block of the skeleton is the advanced area, visible: false.
using (gr.Row(visible: false))
{
gr.Markdown("### Advanced options");
gr.Textbox(label: "Separator", value: ",", info: "What separates multiple values");
gr.Number(label: "Line limit", value: 200);
}
You can’t see it in Figure 4-3. It isn’t collapsed, and it isn’t hidden. It simply isn’t drawn at all. None of this Row’s three children exist on the page — not even a div is generated — so it takes up no space. Where the advanced area should be, there’s nothing; below the main body is blank space, and below that the footer.
visible has three uses; this chapter uses the first.
- Hard-coded in the constructor:
falsemeans it never appears. Good for “modules not finished yet” — put the code in, keep it off the page for now; - Changed at runtime with
Update,gr.Update() with { Visible = true }. Good for interactions like “click to expand”; needs events, covered in Chapter 5; - Put in an
Accordionso users can collapse it themselves. Covered in Chapter 18.
visible: false affects only whether it’s drawn, not the structure. The layout tree in /config still has that row, with the visible attribute set to false, and all three children are still in the tree. So a “hidden block” can still be referenced by events and opened by Update — it just isn’t on the page at this moment. Chapter 5 uses this. To put “Advanced options” under a button’s control, you don’t rebuild the page; you just change visible to true.
interactive governs a different thing: whether it can be changed. “Statistics” and “Notice” in the result area are written with interactive: false — they display results and shouldn’t be editable.
Here’s a counterintuitive detail. A box with interactive: false looks almost exactly like an editable one. White background, dark text, the same border color — the only difference is you can’t click into it, and the cursor is a normal arrow instead of a text cursor. In Figure 4-3, “Body” and “Statistics” both look white for exactly this reason.
“Body” is the opposite: it’s editable, written with interactive: true. That’s not arbitrary. The line-wrapping tool in Chapter 3 lets users hand-edit the wrapped body, then check “Keep my edited body” so the next run won’t overwrite it. The skeleton keeps it editable for now; that switch only makes sense after Chapter 5 wires up events. Click in and change a few characters now and a refresh wipes them, because nothing records the changes yet.
The two parameters together give only three outcomes.
visible | interactive | What’s on the page |
|---|---|---|
true | true | Displayed normally, editable |
true | false | Displayed normally, can’t click in, looks almost unchanged |
false | any | Not drawn at all, takes no space, but still in the structure tree |
interactive also has a default behavior, and this chapter’s code happens to trigger it.
On a static page with no events, the framework can’t tell input from output and can only rely on a convention. A component that already has content is treated as an output and rendered read-only; an empty one as an input and editable. “Has content” here is judged by the component’s default value: a textbox that isn’t an empty string, a number that isn’t 0, a checkbox that’s checked — all count as having content.
In the sample, both “Source text” and “Body” are written with a non-empty value; without an explicit interactive: true, they’d be boxes you can’t click into. A reader opens the page wanting to edit the source text, finds they can’t, and starts doubting their own setup.
gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
In that line, interactive: true isn’t optional decoration; it overrides the convention above.
The checkbox next to it is unaffected. In gr.Checkbox(label: "Keep my edited body", value: false), false happens to be the checkbox’s default, so it doesn’t count as “having content”, and it stays clickable. Change value to true and it becomes non-clickable.
Once Chapter 5 wires up events, this convention gives way to the events. Components used as inputs become automatically editable, those used as outputs automatically read-only, and then you’re fine without writing interactive. But in a static skeleton, write interactive alongside any non-empty value and you save yourself one round of confusion.
One more thing: both visible and interactive can be changed in Update and written on the component. The difference is that in the constructor it’s the initial state, while in Update it’s a change for this one run. The former decides what the page looks like when opened, the latter how it changes during a run. This chapter only has the former.
4.7 Choosing Between Interface and Blocks
Now we can answer a practical question. You have a requirement — Interface or Blocks?
First, one thing: the return type of gr.Interface(...) is itself Blocks. It’s “a fixed layout built with Blocks” — one column of inputs, one column of outputs, one submit button, plus ready-made extras like examples, clear, and flags. So the choice is “use a ready-made layout” versus “place things yourself”.
The criterion is three questions in order; the first “yes” settles it.
- Is the UI “a set of inputs → one click → a set of outputs”? Yes, use
Interface. - Do you need side-by-side areas, or a containment relationship between areas? Yes, use
Blocks. - Do you need to bind events per component, need state, need multiple pages? Yes, use
Blocks.
The third follows from the first two. As soon as the UI has two actions, Interface’s single button maps to just one handler function and the second action has no entry point; as soon as data must survive across two operations, you need State (Chapter 14); as soon as there’s too much functionality for one page, you need multiple pages (Chapter 18). All three can only be done in Blocks.
Conversely, when should you not use Blocks? The answer is “when you only need one function”. Interface writes the layout, button, example rows, and clear logic for you — all of which would otherwise be code you’d write. Rewriting a tool with three inputs and one output in Blocks adds a few dozen lines of container code and buys only the possibility that “you might add another area later”. Don’t pay for a requirement that hasn’t appeared yet.
The migration cost between the two is low too. Moving from Interface to Blocks, not a line of business code changes; only three places do.
- Components change from “stuffed into the
inputs/outputslists” to “placed into containers”; - The original
submitBtnbecomesgr.Button(...), placed in a container; - The one run that
Interfacewired up automatically becomes aClickconnecting the button, inputs, and outputs (Chapter 5).
Move the line-wrapping tool from Chapter 3 over and TextLayout.Wrap stays completely untouched; only the Layout handler function changes where its return value goes. What migrates is the UI; the business half moves over as-is.
| Scenario | Choice | Reason |
|---|---|---|
| One function, a few inputs and outputs | Interface | Layout, button, examples all ready-made |
| Demoing to people, need an examples row | Interface | Example rows and flags are built in |
| Two or more side-by-side areas | Blocks | Interface has only two columns |
| Grouping needed inside an area | Blocks | Needs containers like Group |
| Multiple buttons, multiple actions | Blocks | Interface has only one submit |
| Data must survive across operations | Blocks | State only exists in Blocks |
| Too much functionality, needs paging | Blocks | Multi-page navigation is on Blocks |
This table says one thing: Interface is one fixed arrangement of Blocks. When you can’t decide, write it as Interface first — the part where you get stuck tells you what’s missing.
4.8 Chapter Summary
Blocks writes a page, not a function. A component belongs to the innermost open container. using opens a layer, the closing brace closes it, and later components go back to the previous layer. Omitting using leaves that layer open and everything after gets stuffed into it; writing outside all using blocks throws no error, the component just doesn’t appear on the page. The page is sealed when the first request arrives, and adding components after sealing is rejected, so the UI must be written before Launch.
The four containers have a clear division of labor: Row arranges horizontally and splits width by scale; Column arranges vertically with each child its own block; Group arranges vertically with children joined into one block sharing an outer frame; Form isn’t written — at the end of rendering the framework wraps consecutive form components into a form node, breaking at non-form components like Markdown and Button. Grouping doesn’t distinguish inputs from outputs; even read-only output boxes get wrapped in.
The auto-generated form carries its children’s scale and minWidth, takes no part in width splitting inside a Column, and competes for shares inside a Row. So for oddities like “the heading went beside the fields”, first count who at that level carries a scale. Also, this form is not an HTML <form>. Pressing Enter doesn’t submit; submitting a group of fields together relies on an event listing them in inputs, which is Chapter 5’s business.
scale governs how to split when wide — shares, not pixels; minWidth governs when to stop placing side by side when narrow. The two main columns are 2:1, at a 1280 viewport 800 and 400; narrow the viewport to 700, the available width 576 is less than 480+320, and the two columns stack into one.
A block with visible: false isn’t drawn at all and leaves no empty space on the page, but it’s still in the structure tree and can be reopened by an event. A box with interactive: false can’t be clicked into but looks almost unchanged, so important read-only states should be written into the label or description. In a static skeleton, components that already have content default to read-only (textbox non-empty, number non-zero, checkbox checked); write interactive: true explicitly to make them editable.
Interface is one fixed arrangement of Blocks, and its return type is Blocks. One function with one set of inputs and outputs — use it; side-by-side areas, multiple actions, state, multiple pages — use Blocks.
The next chapter wires events into this skeleton. Clicking a button will actually run a line-wrapping pass, and the outputs will actually change with it. Only then do the positions laid out in this chapter come into play.